Ping test using python


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Ping test using python
# 1  
Old 11-24-2015
Ping test using python

I am issuing a reboot command to a client server from admin server using my python function. I am able to do that but now I need do a ping test every second and print if the ping is successful. With the below code I can check ping only once.
Code:
import os hostname = "myclient" 
response = os.system("ping -c 1 " + hostname)  

if response == 0:   
      print hostname, 'Reboot successful!'
else:
      print hostname, 'Rebooting..!'

Also if I am able to print "." (one dot) per ping check in one line instead of "Rebooting..!" line by line that would be awesome.

I am trying for the output:
Code:
Rebooting ...............
Reboot successful!

# 2  
Old 11-24-2015
consider:

Code:
import os, sys, time
hostname = "myclient"
response = os.system("ping -c 1 " + hostname + " >/dev/null 2>&1")

if response == 0:
      print hostname, 'Reboot successful!'
      sys.exit(0)
else:
      sys.stderr.write(hostname + ' Rebooting..')

sleep_wait=1
max_ping_wait=10
count=0
while (count < max_ping_wait and os.system("ping -c 1 " + hostname + " >/dev/null 2>&1")):
      sys.stderr.write('.')
      time.sleep(sleep_wait)
      count+=1

if (count < max_ping_wait):
    print hostname, 'Reboot successful!'
    sys.exit(0)
else:
    print hostname, 'Reboot unsuccessful.'
    sys.exit(1)

Why stderr for the dots? Stderr is usually unbuffered...
Adjust max_ping_wait and sleep_wait however you like.

---------- Post updated at 11:10 AM ---------- Previous update was at 11:10 AM ----------

oh.. tweak the output, my output isn't exactly like how you wanted.
This User Gave Thanks to cjcox For This Post:
# 3  
Old 11-24-2015
Intelligent .. I am gonna try this right away..
# 4  
Old 11-24-2015
subprocess is the module intended to be used instead of os.system

Maybe this might help:

Code:
import subprocess
import sys

host = 'myclient'
cmd = ['ping', '-c2', '-W 5', host ]
done = False
timeout = 10 # default time out after ten times, set to -1 to disable timeout

print "Rebooting .",
while not done and timeout:
        response = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        stdout, stderr = response.communicate()
        if response.returncode == 0:
            print "Server up!"
            done = True
        else:
            sys.stdout.write('.')
            timeout -= 1
if not done:
       print "\nServer failed to respond"


Last edited by Aia; 11-24-2015 at 04:06 PM.. Reason: Adds prints to accomodate OP output
This User Gave Thanks to Aia For This Post:
# 5  
Old 11-24-2015
Both solution works after I add a sleep command as my reboot command takes couple of seconds to actually bring down my client server. So I need to tweak this while loop so that it will start waiting on the first failure of ping and come out when its success. I cant rely on the sleep command as I am dealing with thousands of client servers and unnecessary sleep cannot be afforded.
# 6  
Old 11-24-2015
sleep will will make things more interruptible. Even a sleep 1. So, it simply means you could lose one second at most vs not having it, and you can interrupt it (if that's important to you). Makes it more multiprocess friendly.
# 7  
Old 11-25-2015
I am afraid sleep may make it complicated as some servers may take more than 10 seconds to respond and some in 1 second. Network response also matters.

---------- Post updated at 09:48 AM ---------- Previous update was at 09:45 AM ----------

Rather than sleep, having a wait for ping to fail and then print "Reboot started " then execute the while loop makes more sense to me. But that would need another loop I guess.
Login or Register to Ask a Question

Previous Thread | Next Thread

9 More Discussions You Might Find Interesting

1. Programming

Create a C source and compile inside Python 1.4.0 to 3.7.0 in Python for ALL? platforms...

Hi all... As you know I like making code backwards compatible for as many platforms as possible. This Python script was in fact dedicated for the AMIGA A1200 using Pythons 1.4.0, 1.5.2, 1.6.0, 2.0.1, and 2.4.6 as that is all we have for varying levels of upgrades from a HDD and 4MB FastRam... (1 Reply)
Discussion started by: wisecracker
1 Replies

2. Programming

Ping test sends mail when ping fails

help with bash script! im am working on this script to make sure my server will stay online, so i made this script.. HOSTS="192.168.138.155" COUNT=4 pingtest(){ for myhost in "$@" do ping -c "$COUNT" "$myhost" &&return 1 done return 0 } if pingtest $HOSTS #100% failed... (4 Replies)
Discussion started by: mort3924
4 Replies

3. Shell Programming and Scripting

How to get reason for ping failure using perls Net::Ping->new("icmp");?

Hi I am using perl to ping a list of nodes - with script below : $p = Net::Ping->new("icmp"); if ($p->ping($host,1)){ print "$host is alive.\n"; } else { print "$host is unreacheable.\n"; } $p->close();... (4 Replies)
Discussion started by: tavanagh
4 Replies

4. Shell Programming and Scripting

python test datetime 30 minutes ago

Hello, RHEL5.5 PYTHON=2.4.3 I have 2 python variables using the datetime module. Here is how I call them: print "Current Time: %s" % now print "LastDownloadTime: %s" % LastDownloadTime Here is an example of an issue. Current Time: 2012-01-05 14:06:09.749240... (2 Replies)
Discussion started by: jaysunn
2 Replies

5. Shell Programming and Scripting

Animation Ping on Solaris Like Cisco Ping

Hi, I develop simple animation ping script on Solaris Platform. It is like Cisco ping. Examples and source code are below. bash-3.00$ gokcell 152.155.180.8 30 Sending 30 Ping Packets to 152.155.180.8 !!!!!!!!!!!!!.!!!!!!!!!!!!!!!. % 93.33 success... % 6.66 packet loss...... (1 Reply)
Discussion started by: gokcell
1 Replies

6. Programming

python little ping script

Hi everyone, I'm a newby in the python languages, and I try to make some parallels to shell. My question is how ca I give the information to python that the line 3 "r=...." the string "line" is a variable. import os, re line = "localhost" r = "".join(os.popen("ping line -c... (2 Replies)
Discussion started by: research3
2 Replies

7. Shell Programming and Scripting

How to check weather a string is like test* or test* ot *test* in if condition

How to check weather a string is like test* or test* ot *test* in if condition (5 Replies)
Discussion started by: johnjerome
5 Replies

8. Shell Programming and Scripting

Test on string containing spacewhile test 1 -eq 1 do read a $a if test $a = quitC then break fi d

This is the code: while test 1 -eq 1 do read a $a if test $a = stop then break fi done I read a command on every loop an execute it. I check if the string equals the word stop to end the loop,but it say that I gave too many arguments to test. For example echo hello. Now the... (1 Reply)
Discussion started by: Max89
1 Replies

9. Shell Programming and Scripting

help: infinant loop script - host ping test

need to check on some hosts and send an email if there status changes I wanna put together a script in bash that will allow me to check the up/down state of a single host via ping i want it to run in a continuous loop so I can just fire the script and forget about it(dont want cron to drive... (2 Replies)
Discussion started by: zeekblack
2 Replies
Login or Register to Ask a Question