-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTraceRoute.py
More file actions
100 lines (83 loc) · 2.84 KB
/
TraceRoute.py
File metadata and controls
100 lines (83 loc) · 2.84 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
#!/usr/bin/python
import nmap
import socket
import struct
import sys
# ask user the target
Target = raw_input("Target IP: ")
print("Target ports")
print("(ex: 21-443)")
Target_ports = raw_input()
print("")
# initialize the port scanner
nmScan = nmap.PortScanner()
nmScan.scan(Target, Target_ports)
print(nmScan.csv())
# run a loop to print all the found result about the ports
for host in nmScan.all_hosts():
print('Host : %s (%s)' % (host, nmScan[host].hostname()))
print('State : %s' % nmScan[host].state())
for proto in nmScan[host].all_protocols():
print('----------')
print('Protocol : %s' % proto)
lport = nmScan[host][proto].keys()
lport.sort()
for port in lport:
print ('port : %s\tstate : %s' % (port, nmScan[host][proto][port]['state']))
print ("-------------------------------------")
print ("Hops")
class flushfile(file):
def __init__(self, f):
self.f = f
def write(self, x):
self.f.write(x)
self.f.flush()
sys.stdout = flushfile(sys.stdout)
def main(dest_name):
dest_addr = socket.gethostbyname(dest_name)
port = 33434
max_hops = 30
icmp = socket.getprotobyname('icmp')
udp = socket.getprotobyname('udp')
ttl = 1
while True:
recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
# Build the GNU timeval struct (seconds, microseconds)
timeout = struct.pack("ll", 5, 0)
# Set the receive timeout so we behave more like regular traceroute
recv_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeout)
recv_socket.bind(("", port))
sys.stdout.write(" %d " % ttl)
send_socket.sendto("", (dest_name, port))
curr_addr = None
curr_name = None
finished = False
tries = 3
while not finished and tries > 0:
try:
_, curr_addr = recv_socket.recvfrom(512)
finished = True
curr_addr = curr_addr[0]
try:
curr_name = socket.gethostbyaddr(curr_addr)[0]
except socket.error:
curr_name = curr_addr
except socket.error as (errno, errmsg):
tries = tries - 1
sys.stdout.write("* ")
send_socket.close()
recv_socket.close()
if not finished:
pass
if curr_addr is not None:
curr_host = "%s (%s)" % (curr_name, curr_addr)
else:
curr_host = ""
sys.stdout.write("%s\n" % (curr_host))
ttl += 1
if curr_addr == dest_addr or ttl > max_hops:
break
if __name__ == "__main__":
main(Target)