Ping monitor - monitor ip in the background?

Andrey Balaguta andrey.balaguta at
Sun Nov 2 08:54:09 CET 2008

Hi, ScottZ.

I I have to write such a thing, I'll wrap the whole thing into some
class, say Pinger. It will have "do" method, which will perform one
particular pinging action. It'll also have a start/stop mechanism,
which will start a thread to continuously pinging a host. To notify
environment (say, yours tray icon) about host state change (dead/
alive), it will have callback mechanism (register_callback/
unregister_callback). Here, I've written a simple implementation,
maybe this will be helpful.

====== ================
import os
import threading
import subprocess
import re
import time

class Pinger:
  def __init__(self, ip = None):
    self.ip = None
    self.running = False
    self.callbacks = list()
  def setAddress(self, ip):
    if self.ip != ip:
      if self.running:
      self.ip = ip
  def do(self):
    if == "nt":  # Windows
        pcmd = "ping -n 1 -w 1000 "
    else:                # *nix
        pcmd = "ping -c1 -W1 "
    p = subprocess.Popen(pcmd + self.ip, shell=True,
    # give it time to respond
    a ='(.*)ms',
    if a:
        return True
        return False
  def start(self):
    def run():
      result = False
      while self.running:
        next =
        if next != result and self.running:
          [ callback(next) for callback in self.callbacks ]
        result = next
    self.ping_thread = threading.Thread(target = run)
    self.running = True
  def stop(self):
    self.running = False
  def register_callback(self, callback):
    if callback not in self.callbacks:
  def unregister_callback(self, callback):
    if callback in self.callbacks:

if __name__ == '__main__':
   p = Pinger('')
   def printout(alive):
        if alive:
          print 'Host is alive.'
          print 'Host is dead.'
   while True:
     print "Ding..."


Note that printout will be called ONLY if host state has changed, not
on EVERY ping.

Best Regards, Andrey Balaguta

More information about the Python-list mailing list