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
|
'''
Copyright (C) 2007 James L. Pettit (james.l.pettit@gmail.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License Version 3 (see
LICENSE.txt
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
from twisted.internet import reactor, defer, protocol
import socket, fcntl, struct
import sys
class CallbackAndDisconnectProtocol(protocol.Protocol):
def connectionMade(self):
self.transport.loseConnection()
class ConnectionTestFactory(protocol.ClientFactory):
protocol = CallbackAndDisconnectProtocol
def __init__(self):
self.deferred = defer.Deferred()
def clientConnectionLost(self, transport, reason):
self.deferred.callback('success')
def clientConnectionFailed(self, transport, reason):
self.deferred.callback('failure')
def testConnect(host, port):
factory = ConnectionTestFactory()
reactor.connectTCP(host, port, factory, timeout=30)
return factory.deferred
def get_local_ip(ifname):
#s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#s.connect(("localhost",22))
#return s.getsockname()[0]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
def handleResult(result, host, callback):
if result == 'success':
callback(host)
def get_local_hosts(callback1, callback2):
#local_addr = get_local_ip('eth0')
#local_addr = '128.114.138.1'
local_addr = '192.168.0.2'
octets = local_addr.split('.')
base = '%s.%s.%s.' % tuple(octets[:-1])
hosts = [base+str(x) for x in xrange(1, 255)]
tests = [testConnect(host, 22) for host in hosts]
for test, host in zip(tests, hosts):
test.addCallback(handleResult, host, callback1)
defer.DeferredList(tests, consumeErrors=True).addCallback(callback2)
if __name__ == '__main__':
get_local_hosts(lambda host: sys.stdout.write(host+'\n'), lambda results: reactor.stop())
reactor.run()
|