Debian Codegraph @

blaeu-traceroute

raw symbols SCIP
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 """ Python code to start a RIPE Atlas UDM (User-Defined
5 Measurement). This one is for running IPv4 or IPv6 traceroute queries
6 to analyze routing
7
8 You'll need an API key in ~/.atlas/auth.
9
10 Stéphane Bortzmeyer <[email protected]>
11 """
12
13 import json
14 import time
15 import os
16 import string
17 import sys
18 import time
19 import socket
20 import pickle as pickle
21 import copy
22
23 import Blaeu
24 from Blaeu import Host_Type
25
26 # If we use --format:
27 # import cymruwhois
28
29 config = Blaeu.Config()
30 # Default values
31 config.protocol = "UDP"
32 config.format = False
33 config.whois = True # But some networks block outgoing port 43
34 config.do_lookup = False
35 config.do_reverse_lookup = False
36 config.first_hop = 1
37 config.max_hops = 32
38
39 def lookup_hostname(str):
40 try:
41 info = socket.getaddrinfo(str, 0, socket.AF_UNSPEC, socket.SOCK_STREAM,0, socket.AI_PASSIVE)
42 if len(info) > 1:
43 print("%s returns more then one IP address please select one" % str)
44 count=0
45 for ip in info:
46 count= count + 1
47 fa, socktype, proto, canonname, sa = ip
48 print("%s - %s" % (count, sa[0]))
49 selection=int(input("=>"))
50 selection = selection - 1
51 selected_ip=info[selection][4][0]
52 else:
53 selected_ip=info[0][4][0]
54 print("Using IP: %s" % selected_ip)
55 except socket.error:
56 return False
57 return selected_ip
58
59 def lookup_ip(ip):
60 try:
61 name, alias, addresslist = socket.gethostbyaddr(ip)
62 except Exception as e:
63 msg = "No PTR"
64 return msg
65 return name
66
67 def usage(msg=None):
68 print("Usage: %s target-IP-address-or-name" % sys.argv[0], file=sys.stderr)
69 config.usage(msg)
70 print("""Also:
71 --format or -k : downloads the results and format them in a traditional traceroute way
72 --simpleformat : the same, but without looking up the AS (useful if you have no whois access)
73 --protocol=PROTO or -j PROTO : uses this protocol (UDP, TCP or ICMP, default is %s)
74 --do_lookup or -d : Enables IP lookup feature (default is disabled, may become interactive if the machine has several addresses)
75 --do_reverse_lookup or -l : Enables reverse IP lookup feature for hops
76 --first_hop=N or -y N : TTL/max hop count for the first hop (default %d)
77 --max_hops=N or -x N : TTL/max hop count for the last hop (default %d)
78 """ % (config.protocol, config.first_hop, config.max_hops), file=sys.stderr)
79
80 """For "TCP Ping"
81 <https://labs.ripe.net/Members/wilhelm/measuring-your-web-server-reachability-with-tcp-ping>,
82 you need --protocol TCP --size=0 --port=$PORT --first_hop=64
83
84 """
85
86 def specificParse(config, option, value):
87 result = True
88 if option == "--protocol" or option == "-j":
89 if value.upper() != "UDP" and value.upper() != "ICMP" and value.upper() != "TCP":
90 usage("Protocol must be UDP or ICMP or TCP: %s rejected" % value.upper())
91 sys.exit(1)
92 config.protocol = value.upper()
93 elif option == "--first_hop" or option == "-y":
94 config.first_hop = int(value)
95 elif option == "--max_hops" or option == "-x":
96 config.max_hops = int(value)
97 elif option == "--format" or option == "-k":
98 config.format = True
99 elif option == "--simpleformat":
100 config.format = True
101 config.whois = False
102 elif option == "--do_lookup" or option == "-d":
103 config.do_lookup = True
104 elif option == "--do_reverse_lookup" or option == "-l":
105 config.do_reverse_lookup = True
106 else:
107 result = False
108 return result
109
110 args, data = config.parse("j:x:kdy:l", ["format", "simpleformat", "protocol=", "first_hop=", "max_hops=",
111 "do_lookup","do_reverse_lookup"], specificParse, usage)
112
113 if len(args) != 1:
114 usage()
115 sys.exit(1)
116 target = args[0]
117 if config.display_probe_asns:
118 print("Displaying the AS number is always done with the --format option", file=sys.stderr)
119 print("", file=sys.stderr)
120
121 target_type = Blaeu.host_type(target)
122 if config.do_lookup:
123 if target_type != Host_Type.Name:
124 print(("Ignoring --do-lookup, since \"%s\" is already an IP address" % target), file=sys.stderr)
125 else:
126 hostname = target
127 target = lookup_hostname(hostname)
128 target_type = Blaeu.host_type(target)
129 if not target:
130 print(("Unknown host name \"%s\"" % hostname), file=sys.stderr)
131 sys.exit(1)
132 else:
133 if target_type == Host_Type.Name:
134 print("Target must be an IP address, NOT AN HOST NAME (or use --do_lookup)", file=sys.stderr)
135 sys.exit(1)
136
137 data["definitions"][0]["description"] = ("Traceroute %s" % target) + data["definitions"][0]["description"]
138 data["definitions"][0]["type"] = "traceroute"
139 data["definitions"][0]["protocol"] = config.protocol
140 data["definitions"][0]["target"] = target
141
142 if config.first_hop is not None:
143 data["definitions"][0]['first_hop'] = config.first_hop
144 if config.max_hops is not None:
145 data["definitions"][0]['max_hops'] = config.max_hops
146
147 if target_type == Host_Type.IPv6:
148 config.ipv4 = False
149 af = 6
150 if config.include is not None:
151 data["probes"][0]["tags"]["include"] = copy.copy(config.include)
152 data["probes"][0]["tags"]["include"].append("system-ipv6-works")
153 else:
154 data["probes"][0]["tags"]["include"] = ["system-ipv6-works",]
155 else:
156 config.ipv4 = True
157 af = 4
158 if config.include is not None:
159 data["probes"][0]["tags"]["include"] = copy.copy(config.include)
160 data["probes"][0]["tags"]["include"].append("system-ipv4-works")
161 else:
162 data["probes"][0]["tags"]["include"] = ["system-ipv4-works",]
163 data["definitions"][0]['af'] = af
164
165 if config.measurement_id is None:
166 if config.verbose:
167 print(data)
168
169 try:
170 measurement = Blaeu.Measurement(data)
171 except Blaeu.RequestSubmissionError as error:
172 print(Blaeu.format_error(error), file=sys.stderr)
173 sys.exit(1)
174 print("Measurement #%s %s uses %i probes" % (measurement.id,
175 data["definitions"][0]["description"],
176 measurement.num_probes))
177
178 rdata = measurement.results(wait=True, percentage_required=config.percentage_required)
179 print(("%s probes reported" % len(rdata)))
180 else:
181 measurement = Blaeu.Measurement(data=None, id=config.measurement_id)
182 rdata = measurement.results(wait=False)
183 if config.verbose:
184 print("%i results from already-done measurement #%s" % (len(rdata), measurement.id))
185
186 print(("Test #%s done at %s" % (measurement.id, time.strftime("%Y-%m-%dT%H:%M:%SZ", measurement.time))))
187 print(f"Results on atlas.ripe.net : https://atlas.ripe.net/measurements/{measurement.id}")
188 if config.format: # Code stolen from json2traceroute.py
189 if config.whois:
190 from cymruwhois import Client
191
192 def whoisrecord(ip):
193 try:
194 currenttime = time.time()
195 ts = currenttime
196 if ip in whois:
197 ASN,ts = whois[ip]
198 else:
199 ts = 0
200 if ((currenttime - ts) > 36000):
201 c = Client()
202 ASN = c.lookup(ip)
203 whois[ip] = (ASN,currenttime)
204 return ASN
205 except Exception as e:
206 return e
207
208 if config.whois:
209 try:
210 pkl_file = open('whois.pkl', 'rb')
211 whois = pickle.load(pkl_file)
212 except IOError:
213 whois = {}
214
215 # Create traceroute output
216 try:
217 for probe in rdata:
218 probefrom = probe["from"]
219 if probefrom:
220 if config.whois:
221 ASN = whoisrecord(probefrom)
222 if not isinstance(ASN, Exception):
223 asn = ASN.asn
224 owner = ASN.owner
225 else:
226 asn = "No AS: %s \"%s\"" % (type(ASN).__name__, ASN)
227 owner = "Unknown"
228 else:
229 asn = ""
230 owner = ""
231 try:
232 print("From: ",probefrom," ",asn," ",owner)
233 except Exception as e:
234 print("From: ", probefrom," ","AS lookup error: ",e)
235 print("Source address: ",probe["src_addr"])
236 print("Probe ID: ",probe["prb_id"])
237 result = probe["result"]
238 for proberesult in result:
239 ASN = {}
240 if "result" in proberesult:
241 print(proberesult["hop"]," ", end=' ')
242 hopresult = proberesult["result"]
243 rtt = []
244 hopfrom = ""
245 for hr in hopresult:
246 if "error" in hr:
247 rtt.append(hr["error"])
248 elif "x" in hr:
249 rtt.append(str(hr["x"]))
250 elif "edst" in hr:
251 rtt.append("!")
252 else:
253 try:
254 rtt.append(hr["rtt"])
255 except KeyError:
256 rtt.append("*")
257 hopfrom = hr["from"]
258 if config.whois:
259 ASN = whoisrecord(hopfrom)
260 if hopfrom:
261 try:
262 if config.whois:
263 if not isinstance(ASN, Exception):
264 asn = ASN.asn
265 owner = ASN.owner
266 else:
267 asn = "No AS: %s \"%s\"" % (type(ASN).__name__, ASN)
268 owner = "Unknown"
269 else:
270 asn = ""
271 owner = ""
272 if not config.do_reverse_lookup:
273 print(hopfrom, " ", asn, " ", owner," ",
274 end=' ')
275 else:
276 reverse_lookup = lookup_ip(hopfrom)
277 print(hopfrom, " ", reverse_lookup, " ", asn, " ",
278 owner, " ", end=' ')
279 except Exception as e:
280 exc_type, exc_value, exc_traceback = sys.exc_info()
281 print(hopfrom, " Lookup failed because of", exc_type.__name__, "(",
282 exc_value, ") ", end=' ')
283 print(rtt)
284 else:
285 print("Error: ", proberesult["error"])
286 print("")
287 finally:
288 if config.whois:
289 pkl_file = open('whois.pkl', 'wb')
290 pickle.dump(whois, pkl_file)