#!/usr/bin/python from gearman import GearmanWorker import subprocess import json import time import re def pingTask(worker, job): total = 2 timeout = 1 ret = {"rawoutput": "", "alive": False, "rc": -1} target = job.data.strip() validIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$" validHostnameRegex = "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$" if not (re.match(validIpAddressRegex, target) or re.match(validHostnameRegex, target)): print 'malformed request' return json.dumps({"err":"invalid parameter - must be ip or host address", "alive":False}) + "\n" pingcmd = subprocess.Popen(["ping", "-W", "%s" % timeout, "-c", "%s" % total, "%s" % target], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while pingcmd.returncode == None: out = pingcmd.stdout.readline() if out != None: ret['rawoutput'] += out print '.' time.sleep(0.05) pingcmd.poll() ret['rawoutput'] = ret['rawoutput'].strip() # get rid of newlines rc = ret['rc'] = pingcmd.returncode if rc == 0: ret['alive'] = True print '%s is alive ' % job.data return json.dumps(ret) + "\n" else: print '%s is offline' % job.data return json.dumps(ret) + "\n" worker = GearmanWorker(["127.0.0.1"]) worker.register_task('ping', pingTask) worker.work()