-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpingChecker.py
More file actions
executable file
·167 lines (134 loc) · 4.67 KB
/
pingChecker.py
File metadata and controls
executable file
·167 lines (134 loc) · 4.67 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#!/usr/bin/env python
# Author: Blue
# Scipt if written for educational purposes
import sys, struct, socket # calculating subnet
import subprocess # ping
import threading # multi threading
import datetime, time # timing
import argparse # parsing arguments
import re # regex from ping output
GRN = '\033[92m'
RED = '\033[91m'
RES = '\033[0m'
parser = argparse.ArgumentParser()
parser.add_argument("-r", dest="range",
help="IP Range", metavar="<RANGE>")
parser.add_argument("-f", dest="ip_file",
help="Read list of IPs from file", metavar="<FILE>")
parser.add_argument("-t", dest="interval",
help="Run periodically, with interval", metavar="<INTERVAL>")
parser.add_argument("-w", dest="timeout",
help="Ping timeout, default=2s", metavar="<TIMEOUT>")
parser.add_argument("-c", dest="number",
help="Number of ping packet, default=1", metavar="<PACKETS>")
parser.add_argument("-v", action="store_true", dest="verbose",
default=False, help="Print all hosts")
args = parser.parse_args()
if len(sys.argv) < 2:
parser.print_usage()
sys.exit(1)
if args.timeout: TIMEOUT=args.timeout
else: TIMEOUT='2'
if args.number: NUMBER=args.number
else: NUMBER='1'
# convert subnet to list of ip
def convert_range(targets, ip_subnet):
if '/' in ip_subnet:
(ip, cidr) = ip_subnet.split('/')
bits = 32 - int(cidr)
start = (struct.unpack('>I', socket.inet_aton(ip))[0] >> bits) << bits
end = start | ((1 << bits) - 1)
for i in range(start+1, end):
targets.append(str(socket.inet_ntoa(struct.pack('>I',i))))
return 0
elif '-' in ip_subnet:
pre = ".".join(ip_subnet.split('-')[0].split('.')[:-1]) + "."
start = int(ip_subnet.split('-')[0].split('.')[-1])
end = int(ip_subnet.split('-')[1])
for i in range(start, end+1):
targets.append(pre+str(i))
return 0
return 1
# import ip from file
def import_ip(targets, filename):
with open(filename,'r') as f:
for line in f:
targets.append(line.lstrip().rstrip())
def ping(index,ip,status):
# this script use system 'ping' command
out = subprocess.Popen(['ping','-c',NUMBER,'-w',TIMEOUT,ip],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout,stderr = out.communicate()
ret = out.returncode
m1 = re.match( r'.*(ttl=.*?) ', stdout, re.M|re.I|re.S)
m2 = re.match( r'.*mdev = .*/(.*)/', stdout, re.M|re.I|re.S)
ttl = ""
time = ""
if m1: ttl = str(m1.group(1))
if m2: time = str(m2.group(1))
# determine status by return code
if ret == 0:
stat = GRN + "UP" + RES
stat += " "*5 + str(ttl)
stat += " "*(10 - len(str(ttl))) + str(time) + "ms"
else:
stat = RED + "DOWN" + RES
status[index] = stat
targets = [] # list of ips
threads = [] # threading slot
status = [] # status for output
# getting list of ips from argument
if args.range:
try:
if convert_range(targets, args.range) != 0: raise
except:
print RED, "[ERROR]", RES, "Invalid range:", args.range
exit(1)
# getting list of ip from file
if args.ip_file:
import_ip(targets,args.ip_file)
if len(targets) == 0:
print "No HOST supplied."
exit(1)
for _ in range(len(targets)):
threads.append(None)
status.append(None)
# start
while True:
total = len(targets)
up = total
# set timer
start_time = datetime.datetime.now()
start_timer = time.time()
if not args.interval:
print GRN ,"[+]", RES, "Start scanning"
print GRN ,"[+]", RES, start_time
for index, host in enumerate(targets):
threads[index] = threading.Thread(target=ping, args=(index,host,status,))
threads[index].start()
#time.sleep(0.1)
# join all threads
for thread in threads:
thread.join()
# print
for i in range(len(targets)):
if "DOWN" in status[i]:
up -= 1
if args.verbose == False:
continue
print " %-16s %s" % (targets[i], status[i])
# set timer and calculate time
end_time = datetime.datetime.now()
end_timer = time.time()
total_time = round(end_timer - start_timer,4)
print GRN ,"[+]", RES, end_time
print GRN ,"[+]", RES, "Finish scanning after",
print GRN, total_time, "seconds", RES,
print " Up host: " + GRN + str(up) + "/" + str(total) + RES
if args.interval:
print "Sleeping..."
time.sleep(float(args.interval))
else:
break
print GRN ,"[+]", RES, "Done!"