View difference between Paste ID: n03pbTsm and kY3ueku3
SHOW: | | - or go back to the newest paste.
1-
#!/usr/bin/python3
1+
#!/usr/bin/python2
2
3
4
import subprocess
5
import tempfile
6
import itertools
7
import os
8
9
10
def ping_async(host):
11
    """Calls nmap in background to ping the specified host"""
12
    args = ('nmap', '-sn', '-PE', '--max-retries=5',
13
            '--initial-rtt-timeout=1500ms', '--max-rtt-timeout=2000ms',
14-
    devnull = subprocess.DEVNULL
14+
15
    popen = subprocess.Popen
16
    outfile = tempfile.TemporaryFile('w+t')
17-
        process = popen(args, stdout=outfile, stderr=devnull)
17+
18
        with open(os.devnull, 'w+b') as devnull:
19
            process = popen(args, stdout=outfile, stderr=devnull,
20
                            stdin=devnull)
21
    except:
22
        outfile.close()
23
        raise
24
    def getresult():
25
        """Blocks until the ping result is available"""
26
        with outfile:
27
            err = process.wait()
28
            if err:
29
                raise subprocess.CalledProcessError(err, str.join(' ', args))
30
            outfile.seek(0)
31
            for line in outfile:
32
                if line.startswith("Host is up"):
33
                    return True
34
        return False
35
    return getresult
36
37
38
def main():
39
    hosts = ("www.google.com", "www.google.de", "www.example.net",
40-
    for host, result in zip(hosts, results):
40+
41
    pings = [ping_async(host) for host in hosts]
42
    results = ("up" if ping() else "down" for ping in pings)
43
    for host, result in itertools.izip(hosts, results):
44
        print("%s is %s" % (host, result))
45
46
47
if __name__ == '__main__':
48
    main()