Solving problem is about exposing yourself to as many situations as possible like Ping a site in Python? and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about Ping a site in Python?, which can be followed any time. Take easy to follow this discuss.
How do I ping a website or IP address with Python?
import ping, socket try: ping.verbose_ping('www.google.com', count=3) delay = ping.Ping('www.wikipedia.org', timeout=2000).do() except socket.error, e: print "Ping Error:", e
The source code itself is easy to read, see the implementations of
verbose_ping and of
Ping.do for inspiration.
Depending on what you want to achive, you are probably easiest calling the system ping command..
Using the subprocess module is the best way of doing this, although you have to remember the ping command is different on different operating systems!
import subprocess host = "www.google.com" ping = subprocess.Popen( ["ping", "-c", "4", host], stdout = subprocess.PIPE, stderr = subprocess.PIPE ) out, error = ping.communicate() print out
You don’t need to worry about shell-escape characters. For example..
host = "google.com; `echo test`
..will not execute the echo command.
Now, to actually get the ping results, you could parse the
out variable. Example output:
round-trip min/avg/max/stddev = 248.139/249.474/250.530/0.896 ms
import re matcher = re.compile("round-trip min/avg/max/stddev = (d+.d+)/(d+.d+)/(d+.d+)/(d+.d+)") print matcher.search(out).groups() # ('248.139', '249.474', '250.530', '0.896')
Again, remember the output will vary depending on operating system (and even the version of
ping). This isn’t ideal, but it will work fine in many situations (where you know the machines the script will be running on)
You may find Noah Gift’s presentation Creating Agile Commandline Tools With Python. In it he combines subprocess, Queue and threading to develop solution that is capable of pinging hosts concurrently and speeding up the process. Below is a basic version before he adds command line parsing and some other features. The code to this version and others can be found here
#!/usr/bin/env python2.5 from threading import Thread import subprocess from Queue import Queue num_threads = 4 queue = Queue() ips = ["10.0.1.1", "10.0.1.3", "10.0.1.11", "10.0.1.51"] #wraps system ping command def pinger(i, q): """Pings subnet""" while True: ip = q.get() print "Thread %s: Pinging %s" % (i, ip) ret = subprocess.call("ping -c 1 %s" % ip, shell=True, stdout=open('/dev/null', 'w'), stderr=subprocess.STDOUT) if ret == 0: print "%s: is alive" % ip else: print "%s: did not respond" % ip q.task_done() #Spawn thread pool for i in range(num_threads): worker = Thread(target=pinger, args=(i, queue)) worker.setDaemon(True) worker.start() #Place work in queue for ip in ips: queue.put(ip) #Wait until worker threads are done to exit queue.join()
He is also author of: Python for Unix and Linux System Administration
It’s hard to say what your question is, but there are some alternatives.
If you mean to literally execute a request using the ICMP ping protocol, you can get an ICMP library and execute the ping request directly. Google “Python ICMP” to find things like this icmplib. You might want to look at scapy, also.
This will be much faster than using
os.system("ping " + ip ).
If you mean to generically “ping” a box to see if it’s up, you can use the echo protocol on port 7.
For echo, you use the socket library to open the IP address and port 7. You write something on that port, send a carriage return (
"rn") and then read the reply.
If you mean to “ping” a web site to see if the site is running, you have to use the http protocol on port 80.
For or properly checking a web server, you use urllib2 to open a specific URL. (
/index.html is always popular) and read the response.
There are still more potential meaning of “ping” including “traceroute” and “finger”.
I did something similar this way, as an inspiration:
import urllib import threading import time def pinger_urllib(host): """ helper function timing the retrival of index.html TODO: should there be a 1MB bogus file? """ t1 = time.time() urllib.urlopen(host + '/index.html').read() return (time.time() - t1) * 1000.0 def task(m): """ the actual task """ delay = float(pinger_urllib(m)) print '%-30s %5.0f [ms]' % (m, delay) # parallelization tasks =  URLs = ['google.com', 'wikipedia.org'] for m in URLs: t = threading.Thread(target=task, args=(m,)) t.start() tasks.append(t) # synchronization point for t in tasks: t.join()
Here’s a short snippet using
check_call method either returns 0 for success, or raises an exception. This way, I don’t have to parse the output of ping. I’m using
shlex to split the command line arguments.
import subprocess import shlex command_line = "ping -c 1 www.google.comsldjkflksj" args = shlex.split(command_line) try: subprocess.check_call(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE) print "Website is there." except subprocess.CalledProcessError: print "Couldn't get a ping."
read a file name, the file contain the one url per line, like this:
python url.py urls.txt
get the result:
Round Trip Time: 253 ms - mirrors.sonic.net Round Trip Time: 245 ms - www.globalish.com Round Trip Time: 327 ms - www.poolsaboveground.com
import re import sys import urlparse from subprocess import Popen, PIPE from threading import Thread class Pinger(object): def __init__(self, hosts): for host in hosts: hostname = urlparse.urlparse(host).hostname if hostname: pa = PingAgent(hostname) pa.start() else: continue class PingAgent(Thread): def __init__(self, host): Thread.__init__(self) self.host = host def run(self): p = Popen('ping -n 1 ' + self.host, stdout=PIPE) m = re.search('Average = (.*)ms', p.stdout.read()) if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host else: print 'Error: Invalid Response -', self.host if __name__ == '__main__': with open(sys.argv) as f: content = f.readlines() Pinger(content)
import subprocess as s ip=raw_input("Enter the IP/Domain name:") if(s.call(["ping",ip])==0): print "your IP is alive" else: print "Check ur IP"