Ping a site in Python?

Posted on

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.

Ping a site in Python?

How do I ping a website or IP address with Python?

Answer #1:

See this pure Python ping by Matthew Dixon Cowles and Jens Diemer. Also, remember that Python requires root to spawn ICMP (i.e. ping) sockets in linux.

import ping, socket
    ping.verbose_ping('', count=3)
    delay = ping.Ping('', 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 for inspiration.

Answered By: orip

Answer #2:

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 = ""
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 = "; `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

Example regex:

import re
matcher = re.compile("round-trip min/avg/max/stddev = (d+.d+)/(d+.d+)/(d+.d+)/(d+.d+)")
# ('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)

Answered By: dbr

Answer #3:

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 = ["", "", "", ""]
#wraps system ping command
def pinger(i, q):
    """Pings subnet"""
    while True:
        ip = q.get()
        print "Thread %s: Pinging %s" % (i, ip)
        ret ="ping -c 1 %s" % ip,
            stdout=open('/dev/null', 'w'),
        if ret == 0:
            print "%s: is alive" % ip
            print "%s: did not respond" % ip
#Spawn thread pool
for i in range(num_threads):
    worker = Thread(target=pinger, args=(i, queue))
#Place work in queue
for ip in ips:
#Wait until worker threads are done to exit    

He is also author of: Python for Unix and Linux System Administration

Answered By: Ryan Cox

Answer #4:

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”.

Answered By: S.Lott

Answer #5:

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 = ['', '']
for m in URLs:
  t = threading.Thread(target=task, args=(m,))
# synchronization point
for t in tasks:
Answered By: Harald Schilly

Answer #6:

Here’s a short snippet using subprocess. The 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"
  args = shlex.split(command_line)
      print "Website is there."
  except subprocess.CalledProcessError:
      print "Couldn't get a ping."
Answered By: Moondoggy

Answer #7:

read a file name, the file contain the one url per line, like this:

use command:

python urls.txt

get the result:

Round Trip Time: 253 ms -
Round Trip Time: 245 ms -
Round Trip Time: 327 ms -

source code(

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)
class PingAgent(Thread):
    def __init__(self, host):
        Thread.__init__(self) = host
    def run(self):
        p = Popen('ping -n 1 ' +, stdout=PIPE)
        m ='Average = (.*)ms',
        if m: print 'Round Trip Time: %s ms -' %,
        else: print 'Error: Invalid Response -',
if __name__ == '__main__':
    with open(sys.argv[1]) as f:
        content = f.readlines()
Answered By: hustljian

Answer #8:

import subprocess as s
ip=raw_input("Enter the IP/Domain name:")
    print "your IP is alive"
    print "Check ur IP"
Answered By: Ibrahim Kasim

Leave a Reply

Your email address will not be published. Required fields are marked *