#!/usr/bin/python3 import subprocess import tempfile def ping_async(host): """Calls nmap in background to ping the specified host""" args = ('nmap', '-sn', '-PE', '--max-retries=5', '--initial-rtt-timeout=1500ms', '--max-rtt-timeout=2000ms', '--min-rtt-timeout=1000ms', host) popen = subprocess.Popen devnull = subprocess.DEVNULL outfile = tempfile.TemporaryFile('w+t') try: process = popen(args, stdout=outfile, stderr=devnull) except: outfile.close() raise def getresult(): """Blocks until the ping result is available""" with outfile: err = process.wait() if err: raise subprocess.CalledProcessError(err, str.join(' ', args)) outfile.seek(0) for line in outfile: if line.startswith("Host is up"): return True return False return getresult def main(): hosts = ("www.google.com", "www.google.de", "www.example.net", "www.foo.bar") pings = [ping_async(host) for host in hosts] results = ("up" if ping() else "down" for ping in pings) for host, result in zip(hosts, results): print("%s is %s" % (host, result)) if __name__ == '__main__': main()