Advertisement
homer512

nmap async

Mar 12th, 2015
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3.  
  4. import subprocess
  5. import tempfile
  6.  
  7.  
  8. def ping_async(host):
  9.     """Calls nmap in background to ping the specified host"""
  10.     args = ('nmap', '-sn', '-PE', '--max-retries=5',
  11.             '--initial-rtt-timeout=1500ms', '--max-rtt-timeout=2000ms',
  12.             '--min-rtt-timeout=1000ms', host)
  13.     popen = subprocess.Popen
  14.     devnull = subprocess.DEVNULL
  15.     outfile = tempfile.TemporaryFile('w+t')
  16.     try:
  17.         process = popen(args, stdout=outfile, stderr=devnull)
  18.     except:
  19.         outfile.close()
  20.         raise
  21.     def getresult():
  22.         """Blocks until the ping result is available"""
  23.         with outfile:
  24.             err = process.wait()
  25.             if err:
  26.                 raise subprocess.CalledProcessError(err, str.join(' ', args))
  27.             outfile.seek(0)
  28.             for line in outfile:
  29.                 if line.startswith("Host is up"):
  30.                     return True
  31.         return False
  32.     return getresult
  33.  
  34.  
  35. def main():
  36.     hosts = ("www.google.com", "www.google.de", "www.example.net",
  37.              "www.foo.bar")
  38.     pings = [ping_async(host) for host in hosts]
  39.     results = ("up" if ping() else "down" for ping in pings)
  40.     for host, result in zip(hosts, results):
  41.         print("%s is %s" % (host, result))
  42.  
  43.  
  44. if __name__ == '__main__':
  45.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement