I'm attempting to write a Python script that will ping/icmp an IP address and tell me if it's alive. I'm doing this because I have a intermittent issue. I wanted to ping, log the outcome, sleep for a period and attempt the ping again. I tried a while loop, but still getting errors like these:
line 33, in (module) systemPing('192.168.1.1')
line 30, in systemPing time.sleep(30)
KeyboardInterrupt
I'm using Python 2.6.
Ideally my question is how I loop through this method/function systemPing and what errors there are in my code? The script seems to work, but I get these errors when I hit ctrl-c.
from subprocess import Popen, PIPE
import datetime, time, re
logFile = open("textlog.txt", "a")
def getmyTime():
now = datetime.datetime.now()
return now.strftime("%Y-%m-%d %H:%M \n")
startTime = "Starting ..." + getmyTime()
logFile.write(startTime)
logFile.write("\n")
def systemPing(x):
cmd = Popen("ping -n 1 " + x , stdout=PIPE)
#print getmyTime()
for line in cmd.stdout:
if 'timed out' in line:
loggedTime = "Failure detected - " + getmyTime()
logFile.write(loggedTime)
if 'Reply' in line:
print "Replied..."
logFile.close()
print "Sleeping 30mins ... CTRL C to end"
time.sleep(30) #1800 is 30mins
systemPing('192.168.1.1')
if __name__ =='__main__':
systemPing('192.168.1.1')
Any help is always appreciated. Thank you.