1

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.

1 Answer 1

1

It's not really an error per se, it's just the default behavior for Python, upon receipt of a SIGINT (which is what happens when you press CTRL-C), to raise a KeyboardInterrupt exception.

You'll get the same thing if you send the signal with kill(1), like...

$ kill -INT <pid>

If you want to handle it, then you can change the code to something like...

if __name__ =='__main__':
    try:
        systemPing('192.168.1.1')
    except KeyboardInterrupt:
        print 'Finished'

...or whatever you want it to do.

Sign up to request clarification or add additional context in comments.

4 Comments

Ok, I understand. I was wondering why it seemed to work but yet I'm getting what I perceived as errors. I hadn't thought of that approach, but haven't ever used it. I will edit the script and test. Thank you.
That try/except statement doesn't loop. It just runs once and exits. On a positive note; without any errors.
@user2105764 It's not supposed to loop. I thought you just wanted to allow CTRL-C to exit the program without an error message. Do you actually want to disable CTRL-C?
I wanted it to loop through the systemPing function. I nested the try/except statement in a while True loop and seems ok, but will need to test longer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.