1
2
3
4
5
6
7
8
9
10
11
12
13 import logging
14
15 from twisted.internet import defer
16 from twisted.internet import reactor
17 from twisted.internet.protocol import Protocol
18 from twisted.internet.protocol import ClientFactory
19 from twisted.internet.protocol import ReconnectingClientFactory
20 from twisted.internet.error import ConnectBindError
21
22 log = logging.getLogger("zen.Portscanner")
23
29
43
56
58 '''
59 '''
60 - def __init__(self, hosts, portRange=(1, 10000), portList=[],
61 queueCount=50, timeout=30):
62 if isinstance(hosts, list):
63 self.hosts = hosts
64 else:
65 self.hosts = [hosts]
66 self.portRange = (portRange[0], portRange[1] + 1)
67 self.portList = portList
68 self.queueCount = queueCount
69 self.timeout = timeout
70 self.data = {
71 'success': {},
72 'failure': {},
73 }
74
76 '''
77 The use of DeferredSemaphore() here allows us to control the
78 number of deferreds (and therefore connections) created at once,
79 thus providing a way for systems to use the script efficiently.
80 '''
81
82 dl = []
83 semaphore = defer.DeferredSemaphore(self.queueCount)
84 if self.portList:
85 ports = self.portList
86 else:
87 ports = range(*self.portRange)
88 for host in self.hosts:
89 for port in ports:
90 d = semaphore.run(self.doFactory, host, port)
91 dl.append(d)
92 dl = defer.DeferredList(dl, consumeErrors=True)
93 return dl
94
99
107
109 hostData = self.data['success'].setdefault(host, [])
110 log.debug('Connected to %s:%d' % (host, port))
111 hostData.append(port)
112
118
122
124 print "Open Ports:"
125 for host, ports in self.getSuccesses().items():
126 print "Host: %s" % host
127 for port in ports:
128 print "\topen port: %i" % port
129 errors = {}
130 for host, portAndError in self.getFailures().items():
131 for port, error in portAndError:
132 errors.setdefault(error, 0)
133 errors[error] += 1
134 print "\nErrors encountered, and their counts:"
135 for error, count in errors.items():
136 print "\t%s -- %i" % (error, count)
137
139 return self.data['success']
140
142 return self.data['failure']
143