-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathping_host
executable file
·65 lines (54 loc) · 1.7 KB
/
ping_host
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env python2.7
import os
import argparse
import subprocess
from Queue import Queue
from threading import Thread
import time
import re
num_threads = 100
queue = Queue()
stat = []
def ping():
while True:
try:
ip = queue.get()
except Queue.Empty:
return
try:
output = subprocess.check_output("ping -c 5 %s" % ip, shell=True, stderr=subprocess.STDOUT)
line = output.rstrip().split("\n").pop()
pattern = re.compile("round-trip min/avg/max/stddev = [0-9\.]+/([0-9\.]+)/[0-9\.]+/[0-9\.]+ ms")
m = pattern.match(line)
if m is not None:
avgtime = m.group(1)
print "%s: %s" % (ip, avgtime)
stat.append((ip, avgtime))
except subprocess.CalledProcessError:
pass
finally:
time.sleep(3)
queue.task_done()
def main():
parser = argparse.ArgumentParser(description="ping multiple hosts")
parser.add_argument("-f", "--file", help="a file contain host list, one line one host")
parser.add_argument("hosts", nargs="*", metavar="HOST", help="host to ping")
args = parser.parse_args()
if args.file is not None:
try:
for line in open(args.file).readlines():
line = line.strip()
if line == "" or line[0] == "#":
continue
args.hosts.append(line)
except IOError:
pass
for ip in args.hosts:
queue.put(ip.strip())
for i in range(num_threads):
worker = Thread(target=ping)
worker.setDaemon(True)
worker.start()
queue.join()
if __name__ == "__main__":
main()