homer512 icon

nmap async py2

homer512 | PRO | 03/12/15 07:14:44 PM UTC | 0 ⭐ | 697 👁️ | Never ⏰ | []
Python |

1.42 KB

|

None

|

0 👍

/

0 👎

#!/usr/bin/python2
 
 
import subprocess
import tempfile
import itertools
import os
 
 
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
    outfile = tempfile.TemporaryFile('w+t')
    try:
        with open(os.devnull, 'w+b') as devnull:
            process = popen(args, stdout=outfile, stderr=devnull,
                            stdin=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 itertools.izip(hosts, results):
        print("%s is %s" % (host, result))
 
 
if __name__ == '__main__':
    main()

Comments