Writing to file during infinite while - python

I need to write in a txt file during a infinite while. But it's not writing and if I don't use infinite while it's works.
What do I have to change ?
My goal is to ping different ip infinite time and when the ping fails, it's written in the file with the time and date
I've tried the code without the while True and it works.
I think the code need to be stop to write but can we do without stop ?
import os
import datetime
fichier = open("log.txt", "a")
date = datetime.datetime.now()
hostnames = [
'192.168.1.1',
'192.168.1.2',
'192.168.1.3',
]
while True :
for hostname in hostnames:
ping = os.system(" Ping " + str(hostname))
if ping == 1:
print("DOWN")
fichier.write(str(date) + " " + str(hostname) + '\n' + '\n')
else:
print("UP")
I expect the output when it's failed with a stamp Date/Time and the IP Address

To sum up all the answers in one:
try:
with open('log.txt', 'a') as fichier:
while True:
for hostname in hostnames:
ping = os.system(" Ping " + str(hostname))
if ping == 1:
print("DOWN")
fichier.flush()
fichier.write(str(date) + " " + str(hostname) + '\n' + '\n')
else:
print("UP")
except KeyboardInterrupt:
print("Done!")

Related

How to execute the rest of nsupdate in python?

So I need to have a script that will execute the nsupdate command, to add a record the the ddns database:
#!/usr/local/bin/python3.7
import sys
import os
import time
import subprocess
try:
hostname = sys.argv[1]
IP = sys.argv[2]
except Exception as e:
print('Error: Please enter a number\n')
zone = hostname[-5:]
update = ''
if zone == 'zone1':
print('\nThis will be added to zone1\n')
#add to zone 1
update = 'update add ' + hostname + ' 86400' + ' A ' + IP
os.system('nsupdate -k zone1.key')
update = 'update add ' + hostname + ' 86400' + ' A ' + IP
if zone == 'zone2':
print('This will be added to zone2')
#add to zone 2
os.system('nsupdate -k zone2.key')
#if statement to check IP address is in range
#update = 'update add ' + hostname + ' 86400' + ' A ' + IP
time.sleep(2)
os.system(update)
time.sleep(2)
os.system('send')
time.sleep(2)
os.system('quit')
#time.sleep(3)
print('\nHostname:')
print(hostname)
print('\nIP address: ')
print(IP)
print('\nZone: ')
print (zone)
Above is the code I'm currently working with, please ignore it if its badly written, dont write much python.
I find it executes the first os.system fine, but will not run the next three.
I believe that's because the command line changes from # to > but have got no clue how to still have it execute those commands.
Have tried os.system and subprocess.run/call
even tried call it all in one os.system by going os.system('nsupdate; {update}; send; quit').
Any help would be great.

How to write Python and shell console outputs to a file in an order?

I am running an impdp statement form inside a Python File and I want to write the print statements in Python script in the logfile, which is being created in 'abccmd' using '>>' append symbol.
Two issues to be resolved:
The print commands are overwriting the logs generated using impdp commands
I want the logs to be in order in which they come in script (All the print commands are coming at top of the log file. Even the commands that are after the impdp statement in the function being called)
Also, I am using dynamic naming system for logfiles that are created.
def import_command_run(DP_WORKLOAD, dp_workload_cmd, imp_loop, vardate):
abccmd = 'impdp admin/DP_PDB_ADMIN_PASSWORD#DP_PDB_FULL_NAME SCHEMAS=ABC >>' + logdir + '/DP_IMP_' + DP_PDB_FULL_NAME[i] + '_' + DP_WORKLOAD + '_' + str(vardate) + '.log 2>&1'
defcmd = 'impdp admin/DP_PDB_ADMIN_PASSWORD#DP_PDB_FULL_NAME SCHEMAS=DEF >>' + logdir + '/DP_IMP_' + DP_PDB_FULL_NAME[i] + '_' + DP_WORKLOAD + '_' + str(vardate) + '.log 2>&1'
# any of the above commands
run_imp_cmd(eval(abccmd))
def run_imp_cmd(cmd):
output = subprocess.Popen([cmd], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
stdout,stderr = output.communicate()
return stdout
All the Print commands used in imp_workload() and the main() methods should come in exact order in the log file.
def imp_workload(DP_WORKLOAD, DP_DURATION_SECONDS, vardate):
imp_loop = 1
while DP_DURATION_SECONDS > 0:
print("------------------------------------------------------------------------------------------------------------------------------------------")
print(" PDB " + DP_PDB_FULL_NAME[i] + " for Workload " + DP_WORKLOAD + ": Import number " + str(imp_loop) + " Starts")
print("------------------------------------------------------------------------------------------------------------------------------------------")
duration = 0
print("\nImport is running for Time loop : " + str(imp_loop))
startImport = datetime.now()
start = time.time()
print("Start Time for the Import is : " + startImport.strftime("%Y-%m-%d %H:%M:%S"))
# Calling the above function here
import_command_run(DP_WORKLOAD, dp_workload_cmd, imp_loop, vardate)
time.sleep(60)
stop = time.time()
endImport = datetime.now()
print("Stop Time for the Import is : " + endImport.strftime("%Y-%m-%d %H:%M:%S"))
duration = stop - start
print("\nTotal Time elapsed for Data Pump Import Time loop " + str(imp_loop) + ": " + str(int(duration/3600)) + " hours " + str(int(((duration/60)%60))) + " minutes " + str(int((duration % 60))) + " seconds\n")
DP_DURATION_SECONDS = DP_DURATION_SECONDS - duration
if DP_DURATION_SECONDS>0:
print("\nData Pump Import will again run for: " + str(int(DP_DURATION_SECONDS)) + " seconds\n")
else:
print("\nDATA Pump Import has ended for the workload: " + DP_WORKLOAD + "\n")
imp_loop = imp_loop + 1
I am trying to use sys.stdout as you can see. But it is overwriting the logfile created by the impdp statement.
if __name__ == "__main__":
vardate = datetime.now().strftime("%d-%b-%Y-%I_%M_%S_%p")
# Running loop through each workload mentioned in the config file
for i in range((len(DP_PDB_FULL_NAME))):
print("\n==========================================================================================================================================")
print("\n Data Pump Workload has Started \n")
print("==========================================================================================================================================")
# Conversion of time form minutes to seconds
DP_DURATION_SECONDS = int(DP_DURATION) * 60
now = datetime.now()
print("Current Date and Time: " + now.strftime("%Y-%m-%d %H:%M:%S"))
print("\nData Pump Import will run for " + DP_DURATION + " minutes\n")
for DP_WORKLOAD in DP_WORKLOAD_NAME:
sys.stdout = open(logdir + '/DP_IMP_' + DP_PDB_FULL_NAME[i] + '_' + DP_WORKLOAD + '_' + str(vardate) + '.log', 'w')
p1 = multiprocessing.Process(target=imp_workload, args=(DP_WORKLOAD, DP_DURATION_SECONDS, vardate, ))
p1.start()
sys.stdout.close()
Please suggest a way to log them in a proper way.
I wonder this may be the result you want, anyway, you can try this one:
python -m abc.py > d:\output.txt
It makes output.txt in d: and it will record all the print results in the order they are called.

Python telnet not showing result

with python script I want to make some configuration on mikrotik routers, looks like script is right and no gives errors but ends without printing command outputs
import telnetlib
import time
dev_ip = "172.16.62.160"
user = "admin"
PASSWORD = ""
comm1 = "ip address print"
tn = telnetlib.Telnet(dev_ip, timeout=1)
tn.read_until(b"Login: ")
tn.write(user.encode("ascii") + b'\n')
tn.read_until(b"Password: ")
tn.write(PASSWORD.encode("ascii") + b'\n')
tn.read_until(b">")
time.sleep(1)
tn.write(comm1.encode("ascii") + b"\r\n")
Showcmdoutput = tn.read_very_eager().decode('ascii')
print(Showcmdoutput)
tn.close()
print("DONE")
running on Ubuntu Desktop
problem solved after putting:
time.sleep(1)
before Showcmdoutput = tn.read_very_eager().decode('ascii')
tn.write(comm1.encode("ascii") + b"\r\n")
time.sleep(1)
Showcmdoutput = tn.read_very_eager().decode('ascii')

I need help completing my code. Note I am a beginner in Python

I am trying to develop a script which sends an email about checking ping regularly at one hour interval of time. I am using Python to program this script and I cannot create a log file to keep the ping logs which I need to mail. I'm new to using subprocess module and its functions.
import threading
import os
def check_ping():
threading.Timer(5.0, check_ping).start()
hostname = "www.google.com"
response = os.system("ping -c 4 " + hostname)
'''
def trace_route():
threading.Timer(5.0, trace_route).start()
hostname = "www.google.com"
response = os.system("traceroute" + hostname)
'''
check_ping()
#trace_route()
output = check_ping()
file = open("sample.txt","a")
file.write(output)
file.close()
import os, platform
import threading
def check_ping():
threading.Timer(10.0,check_ping).start()
hostname = "www.google.com"
response = os.system("ping " + ("-n 1 " if platform.system().lower()=="windows" else "-c 1 ") + hostname)
# and then check the response...
if response == 0:
pingstatus = "Network Active"
else:
pingstatus = "Network Error"
return pingstatus
pingstatus = check_ping()
This is what I came up with:
using subprocess instead of os.system
added timeout of 8 seconds
writing to csv file instead of txt file
added timestamps to csv file, without which I don't really see the point of logging in the first place
import os
import threading
import time
from subprocess import Popen, PIPE
def check_ping():
threading.Timer(10.0,check_ping).start()
# Get current time
timestamp = int(time.time())
# Build the command
hostname = "www.google.com"
if os.name == 'nt':
command = ['ping', '-n', '1', hostname]
else:
command = ['ping', '-c', '1', hostname]
# Create process
pingProcess = Popen(command, stdout=PIPE, stderr=PIPE)
try:
# Timeout 8 seconds, to avoid overlap with the next ping command
outs, errs = pingProcess.communicate(timeout=8)
except TimeoutExpired:
# If timed out, kill
pingProcess.kill()
outs, errs = pingProcess.communicate()
# Get the return code of the process
response = pingProcess.returncode
# and then check the response...
# These four lines can be removed, they are just to see if the system
# works.
if response == 0:
print("Network Active")
else:
print("Network Error")
# You most likely want a CSV file, as most programs accept this file type,
# including Microsoft Excel and LibreOffice Calc
# Further, I'm sure you want timestamps with the results.
file = open("ping.csv","a")
file.write(str(timestamp) + "," + str(response) + "\n")
file.close()
check_ping()
Here is another version without using the system's ping command, but instead using a python library for pinging. This ensures that the code works on all operating systems:
import threading
import time
from ping3 import ping
def check_ping():
threading.Timer(10.0,check_ping).start()
# Get current time
timestamp = int(time.time())
# Build the command
hostname = "www.google.com"
# Run ping
ping_result = ping(hostname, timeout=8)
ping_success = False if ping_result is None else True
# and then check the response...
# These four lines can be removed, they are just to see if the system
# works.
if ping_success:
print("Network Active (" + str(ping_result) + ")")
else:
print("Network Error")
# You most likely want a CSV file, as most programs accept this file type,
# including Microsoft Excel and LibreOffice Calc
# Further, I'm sure you want timestamps with the results.
file = open("ping.csv", "a")
ping_value_str = str(ping_result) if ping_success else "NaN"
file.write(str(timestamp) + "," + ("0" if ping_success else "1") + "," + ping_value_str + "\n")
file.close()
check_ping()

How to end a server socket listen

So what i'm trying to do is to make a multi-threaded server that creates threads for each client that connects to it, and replies back the string sent from the client.
It sort of works, but my server doesn't actually end properly. My KerboardInterrupt catch doesn't seem to work in windows command prompt, only thing that lets me exit the process would be ctrl + pause/break. Can anyone help me think of a way to get the server to end gracefully?
Server Code:
import socket
import threading
import time
import datetime
import sys
def getTime():
ts = time.time()
timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m- %d_%H:%M:%S')
return timeStamp
def ThreadFunction(clientsocket, clientaddr):
global ReceivedData
global SentData
while True:
#Receive data from client
data = clientsocket.recv(bufferSize)
#Get client IP and port
clientIP, clientSocket = clientsocket.getpeername()
#Add to total amount of data transfered
ReceiveDataSize = len(data)
ReceivedData += ReceiveDataSize
#LOg the received data
text_file.write(str(getTime()) + "__ Size of data received (" + clientIP + ":" + str(clientSocket) + ") = " + str(ReceiveDataSize) + '\n')
#Send data
clientsocket.send(data)
SentDataSize = len(data)
SentData += SentDataSize
#Log the sent data
text_file.write(str(getTime()) + "__ Size of data sent (" + clientIP + ":" + str(clientSocket) + ") = " + str(SentDataSize) + '\n')
def Close(counter, ReceivedData, SentData):
print ("Shutting down Server...")
serversocket.close()
text_file.write("\n\nTotal # of connections: " + str(counter))
text_file.write("\nTotal data received: " + str(ReceivedData))
text_file.write("\nTotal data sent: " + str(SentData))
text_file.close()
sys.exit()
if __name__ == '__main__':
serverIP = raw_input('Enter your server IP \n')
port = int(raw_input('What port would you like to use?\n'))
# Maintain how many connections
connections = []
counter = 0
# Maintain amount of data sent to and from server
ReceivedData = 0
SentData = 0
bufferSize = 1024
# Create and initialize the text file with the date in the filename in the logfiles directory
text_file = open("MultiThreadedServerLog.txt", "w")
address = (serverIP, port)
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind server to port
serversocket.bind(address)
# The listen backlog queue size
serversocket.listen(50)
print ("Server is listening for connections\n")
try:
while 1:
# Accept client connections, increment number of connections
clientsocket, clientaddr = serversocket.accept()
counter += 1
# Log client information
print (str(clientaddr) + " : " + " Just Connected. \n Currently connected clients: " + str(counter) + "\n")
text_file.write(str(getTime()) + " - " + str(clientaddr) + " : " + " Just Connected. \n Currently connected clients: " + str(counter) + "\n")
clientThread = threading.Thread(target=ThreadFunction, args=(clientsocket, clientaddr))
clientThread.start()
except KeyboardInterrupt:
print ("Keyboard interrupt occurred.")
Close(counter, ReceivedData, SentData)
Client Code:
from socket import *
import threading
import time
import random
import sys
import datetime
serverIP = ""
port = 8005
message = ""
msgMultiple = 1
def getTime():
ts = time.time()
timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H:%M:%S')
return timeStamp
def run(clientNumber):
buffer = 1024
global totalTime
s = socket(AF_INET, SOCK_STREAM)
s.connect((serverIP, port))
threadRTT = 0
while 1:
for _ in range(msgMultiple):
cData = message + " From: Client " + str(clientNumber)
# Start timer and send data
start = time.time()
s.send(cData.encode('utf-8'))
print "Sent: " + cData
# Stop timer when data is received
sData = s.recv(buffer)
end = time.time()
# Keep track of RTT and update total time
response_time = end - start
threadRTT += end - start
totalTime += response_time
print "Received: " + cData + '\n'
t = random.randint(0, 9)
time.sleep(t)
# Log information of Client
text_file.write(
"\nClient " + str(clientNumber) + " RTT time taken for " + str(msgMultiple) + " messages was: " + str(
threadRTT) + " seconds.")
threadRTT = 0
break
if __name__ == '__main__':
serverIP = raw_input('Enter the server IP: ')
port = int(input('Enter the port: '))
clients = int(input('Enter number of clients: '))
message = raw_input('Enter a message to send: ')
msgMultiple = int(input('Enter the number of times you would like to send the message: '))
# Initialize Log file
text_file = open("ClientLog.txt", "w")
# Used to maintain list of all running threads
threads = []
totalTime = 0
# Create a seperate thread for each client
for x in range(clients):
thread = threading.Thread(target=run, args=[x])
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
# Calculations for log data
bytes = sys.getsizeof(message)
totalRequests = clients * msgMultiple
totalBytes = totalRequests * bytes
averageRTT = totalTime / totalRequests
# Output data
print("Bytes sent in message was : " + str(bytes))
print("Total Data sent was : " + str(totalBytes) + " Bytes.")
print("Average RTT was : " + str(averageRTT) + " seconds.")
print("Requests was : " + str(totalRequests))
# Write data to log file
text_file.write("\n\n Bytes sent in message was : " + str(bytes))
text_file.write("\nTotal Data sent was : " + str(totalBytes) + " Bytes.")
text_file.write("\nAverage RTT was : " + str(averageRTT) + " seconds.")
text_file.write("\nRequests was : " + str(totalRequests))
Also if anyone else has any general improvements they would add to this code, let me know. I'm still pretty new at python, and still rough at it.
Here is the normal intended input i'm getting from my server.
But when it gets to the last client that connects, it starts to drag on for some reason.
The last picture, the inputs go on for the majority of the text file, for a very long time. Seems like something isn't ending properly.
Solved by adding an if statement that checks for a byte < 0 , if it is, end the socket.

Categories