views:

15253

answers:

9

The basic code is:

from Tkinter import *
import os,sys

ana= Tk()
def ping1():
    os.system('ping')

a=Button(pen)
ip=("192.168.0.1")

a.config(text="PING",bg="white",fg="blue")
a=ping1.ip ??? 
a.pack()

ana.mainloop()

How could I ping a sites or address?

+4  A: 

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

Example regex:

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

dbr
+4  A: 

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 ("\r\n") 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".

S.Lott
echo was once widespread but it now disabled by default on most systems. So, it is not a practical way to test if the machine runs fine.
bortzmeyer
A: 

Take a look at Jeremy Hylton's code, if you need to do a more complex, detailed implementation in Python rather than just calling ping.

Brent.Longborough
+7  A: 
Ryan Cox
Don't know that this actually answers the question, but it's very useful information!
ig0774
+16  A: 

See this pure Python implementation by Matthew Dixon Cowles and Jens Diemer (from the PyLucid CMS sources)

import ping, socket
try:
    delay = ping.do_one('www.google.com', timeout=2)
except socket.error, e:
    print "Ping Error:", e
orip
`ping` uses `time.clock` that doesn't yield anything useful on my Linux box. `timeit.default_timer` (it is equal to `time.time` on my machine) works. `time.clock` -> `timeit.default_timer` http://gist.github.com/255009
J.F. Sebastian
A: 

I use the ping module by Lars Strand. Google for "Lars Strand python ping" and you will find a lot of references.

akr
A: 

using system ping command to ping a list of hosts:

import re
from subprocess import Popen, PIPE
from threading import Thread


class Pinger(object):
    def __init__(self, hosts):
        for host in hosts:
            pa = PingAgent(host)
            pa.start()

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__':
    hosts = [
        'www.pylot.org',
        'www.goldb.org',
        'www.google.com',
        'www.yahoo.com',
        'www.techcrunch.com',
        'www.this_one_wont_work.com'
       ]
    Pinger(hosts)
Corey Goldberg
I'm going to register www.this_one_wont_work.com just for kicks and giggles.
Matthew Scouten
A: 

I did something similar this way, as an inspiration:

import urllib

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 = []
for m in URLs:
  t = threading.Thread(target=task, args=(m,))
  t.start()
  tasks.append(t)

# synchronization point
for t in tasks:
  t.join()
Harald Schilly
A: 

You can find an updated version of the mentioned script that works on both Windows and Linux at http://www.g-loaded.eu/2009/10/30/python-ping/

Born To Ride