-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathping_sweep.py
More file actions
91 lines (75 loc) · 2.35 KB
/
ping_sweep.py
File metadata and controls
91 lines (75 loc) · 2.35 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python
"""ping_sweep.py
Usage:
ping_sweep.py <cidr> [--test]
ping_sweep.py -f <file> [--test]
Options:
-h, --help Display usage.
--test Prints out list of addresses to sweep. Does
not send any pings.
--version Display version.
Arguments:
cidr Any CIDR notataion, like 10.10.10.10/31. Other
values, like 10, or 192.168 may be interpretted as
valid CIDR. Use --test to see the list of addresses
produced.
file File containing one IP address or CIDR block per
line. Invalid values are skipped.
"""
import os
import subprocess
from multiprocessing.dummy import Pool as Threadpool
import sys
import docopt
import netaddr
__version__ = '1.0'
def file_to_iplist(ip_file):
"""Return list of IP addresses in file."""
try:
with open(ip_file) as file_handle:
entries = file_handle.read().splitlines()
except IOError as err:
print err.strerror
sys.exit(0)
ip_list = []
for entry in entries:
if netaddr.valid_ipv4(entry):
ip_list.append(entry)
else:
try:
cidr = [str(ip) for ip in list(netaddr.IPNetwork(entry))]
ip_list.extend(cidr)
except netaddr.core.AddrFormatError:
pass
return ip_list
def ping_ip(ip_address):
"""Print IP if ICMP response."""
result = subprocess.call(['ping', '-c', '1', ip_address],
stdout=open(os.devnull, 'w'),
stderr=open(os.devnull, 'w'))
if result == 0:
print ip_address
else:
pass
def scan_targets(ip_list):
"""Ping each IP in network in a separate thread."""
pool = Threadpool(255)
pool.map(ping_ip, ip_list)
pool.close()
pool.join()
def main(args):
"""Parse CLI args and scan targets."""
if args['<cidr>']:
try:
ip_list = [str(x) for x in list(netaddr.IPNetwork(args['<cidr>']))]
except netaddr.core.AddrFormatError as err:
print err.message
sys.exit(0)
elif args['<file>']:
ip_list = file_to_iplist(args['<file>'])
if args['--test']:
print ip_list
sys.exit(0)
scan_targets(ip_list)
if __name__ == "__main__":
main(docopt.docopt(__doc__, version=__version__))