import socket select Queue thread from threading import Thread class S

 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
import socket,select,Queue,thread
from threading import Thread
class Scanner:
def __init__(self,host,timeout=None):
self.host=host
self.timeout=timeout
def _scan_port(self,port,opened,closed):
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.settimeout(self.timeout)
if sock.connect_ex((self.host,port)):
closed.append(port)
return
poller=select.poll()
poller.register(sock.fileno())
for fd,event in poller.poll(self.timeout*1000):
if event in (select.POLLIN,select.POLLOUT):
opened.append(port)
elif event in (select.POLLERR,select.POLLHUP):
closed.append(port)
def _scan_queued_port(self,queue,opened,closed):
self._scan_port(queue.get(),opened,closed)
queue.task_done()
def scan(self,*ports):
opened,closed=[],[]
queue=Queue.Queue()
map(queue.put,ports)
while not queue.empty():
trd=Thread(target=self._scan_queued_port,args=(queue,opened,closed))
# this dirty hack used 'cuz of thread denies to start, if
# the number of threads is more then one-few thousands
while True:
try:
trd.start()
except thread.error:
continue
else:
break
queue.join()
return opened,closed
def slow_scan(self,*ports):
opened,closed=self.scan(*ports)
scanned=opened+closed
unknown=[]
for port in ports:
if port not in scanned:
unknown.append(port)
return opened,closed,unknown