-
Notifications
You must be signed in to change notification settings - Fork 8
/
ping.py
104 lines (92 loc) · 3.51 KB
/
ping.py
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
import urllib.request, subprocess, json, time, sys, re
pings = 1
batchSize = 100
newRepo = False
mode = "ipv4"
target = ""
if len(sys.argv) >= 2:
args = re.findall("((-c|-p|-l)\s?([0-9A-Za-z]+)|-6|-2)",' '.join(sys.argv[1:]))
for arg in args:
if arg[1] == "-c": pings = float(arg[2])
if arg[1] == "-p": batchSize = int(arg[2])
if arg[1] == "-l": target = arg[2]
if arg[0] == "-6": mode = "ipv6"
if arg[0] == "-2": newRepo = True
if newRepo:
file = "https://raw.githubusercontent.com/Ne00n/Looking-Glass-2/master/data/everything.json"
else:
file = "https://raw.githubusercontent.com/Ne00n/Looking-Glass/master/data/everything.json"
def error(run):
print(f"Retrying {run+1} of 4")
if run == 3:
print("Aborting, limit reached.")
exit()
time.sleep(2)
for run in range(4):
try:
print(f"Fetching {file}")
request = urllib.request.urlopen(file, timeout=3)
if (request.getcode() == 200):
raw = request.read().decode('utf-8')
json = json.loads(raw)
break
else:
print("Got non 200 response code")
error(run)
except Exception as e:
print(f"Error {e}")
error(run)
targets,count,mapping = [],0,{}
for domain,lgs in json.items():
for lg,ip in lgs.items():
if ip:
for ip,location in ip[mode].items():
mapping[ip] = {}
if target == "" or target in location:
mapping[ip] = {"domain":domain,"lg":lg,"geo":location}
targets.append(ip)
results = ""
while count <= len(targets):
print(f"fping {count} of {len(targets)}")
batch = ' '.join(targets[count:count+batchSize])
if not batch: break
p = subprocess.run(f"fping -c {pings} {batch}", stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
if not p.stdout.decode('utf-8'):
print("Please install fping (apt-get install fping / yum install fping)")
exit()
results += p.stdout.decode('utf-8')
count += batchSize
parsed = re.findall("([0-9.:a-z]+).*?([0-9]+.[0-9]+|NaN).*?([0-9])% loss",results, re.MULTILINE)
results = {}
for ip,ms,loss in parsed:
if ms == "NaN": ms = 900
if ip not in results: results[ip] = float(ms)
sorted = {k: results[k] for k in sorted(results, key=results.get)}
result,top = [],50
result.append("Latency\tIP address\tDomain\tLocation (Maxmind)\tLooking Glass")
result.append("-------\t-------\t-------\t-------\t-------")
for index,ip in enumerate(sorted.items()):
data = mapping[ip[0]]
result.append(f"{ip[1]}ms\t{ip[0]}\t{data['domain']}\t{data['geo']}\t{data['lg']}")
if float(ip[1]) < 20 and index == top: top += 1
if index == top: break
def formatTable(list):
longest,response = {},""
for row in list:
elements = row.split("\t")
for index, entry in enumerate(elements):
if not index in longest: longest[index] = 0
if len(entry) > longest[index]: longest[index] = len(entry)
for i, row in enumerate(list):
elements = row.split("\t")
for index, entry in enumerate(elements):
if len(entry) < longest[index]:
diff = longest[index] - len(entry)
while len(entry) < longest[index]:
entry += " "
response += f"{entry}" if response.endswith("\n") or response == "" else f" {entry}"
if i < len(list) -1: response += "\n"
return response
result = formatTable(result)
print(f"\nTop {top}")
print(result)