-
Notifications
You must be signed in to change notification settings - Fork 0
/
scanner.py
93 lines (68 loc) · 2.7 KB
/
scanner.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
import logging
from time import sleep
from scapy.fields import ThreeBytesField
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
import scapy.all
import scapy.layers.l2
import scapy.route
import socket
import math
from scapy.all import ARP
from scapy.all import getmacbyip
from scapy.all import sendp
import errno
class Scanner:
def __init__(self):
self.host_list =[]
self.hostname = None
def long2net(self,arg):
if(arg<=0 or arg>=0xFFFFFFFF):
raise ValueError("illegal Network Mask: ",hex(arg))
return 32-int(round(math.log(0xFFFFFFFF-arg,2)))
def CIDR_notation(self,bytes_address,bytes_mask):
network= scapy.utils.ltoa(bytes_address)
net_mask=self.long2net(bytes_mask)
net="%s/%s"%(network,net_mask)
if net_mask< 16:
return None
return net
def get_neighbors_mac_ip(self,net,interface,timeout=1):
self.host_list=[]
try:
ans,uans=scapy.layers.l2.arping(net,iface=interface,timeout=timeout,verbose=False)
sleep(2)
for s,r in ans.res:
mac=r.sprintf("%Ether.src%")
ip=r.sprintf("%ARP.psrc%")
line =r.sprintf("%Ether.src% %ARP.psrc%")
self.host_list.append([ip,mac])
try:
self.hostname=socket.gethostbyaddr(r.psrc)
except socket.error as e:
pass
except socket.error as e:
if e.errno == errno.EPERM:
exit()
return self.host_list
def scan_neighbours(self):
for network, netmask, _, interface, address, _ in scapy.config.conf.route.routes:
# skip loopback network and default gw
if network == 0 or interface == 'lo' or address == '127.0.0.1' or address == '0.0.0.0':
continue
if netmask <= 0 or netmask == 0xFFFFFFFF:
continue
# Skip APIPA network (corresponds to the 169.254.0.0/16 address range)
# See https://fr.wikipedia.org/wiki/Automatic_Private_Internet_Protocol_Addressing for more details
if network == 2851995648:
continue
net = self.CIDR_notation(network, netmask)
# print(net, netmask, interface, address)
if interface != scapy.config.conf.iface:
# see http://trac.secdev.org/scapy/ticket/537
continue
if net:
return self.get_neighbors_mac_ip(net, interface)
if __name__ == '__main__':
s=Scanner()
#s.scan_neighbours()
print(s.scan_neighbours())