Created
June 3, 2014 16:45
-
-
Save xavierskip/911b734335b0d765dd14 to your computer and use it in GitHub Desktop.
scan the lan
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
#-*- coding:utf-8 -*- | |
import os, re, threading | |
addrs = {} | |
def bin8(n): | |
byte = "{0:08b}".format(n) | |
if len(byte)<8: | |
byte = '0'*(8-len(byte))+byte | |
else: | |
byte = byte[-8:] | |
return byte | |
def show8(n): | |
r = '.'.join([ str(int(n[i:i+8],2)) for i in range(0,32,8) ]) | |
# print r | |
return r | |
def b_to_d(n): | |
return int(bin(n)[2:],2) | |
def ip_to_d(ip): | |
return int(''.join([ bin8(int(b)) for b in ip.split('.')]),2) | |
def format32(n): | |
return '{:0>32}'.format(n)[0:32] | |
def ip_compare(x,y): | |
return ip_to_d(x) - ip_to_d(y) | |
def main(lan,**args): | |
# state 1:open 0:close | |
state = args['state'] | |
ip_s,mask_s = lan.split('/')[0],int(lan.split('/')[1]) | |
ip_b = ''.join([ bin8(int(b)) for b in ip_s.split('.')]) | |
mask_b = '{:0<32}'.format(mask_s*'1')[0:32] | |
broadcast_mask = '{:0>32}'.format((32-int(mask_s))*'1')[0:32] | |
ip = int(ip_b,2) | |
mask = int(mask_b,2) | |
broadcast = int(broadcast_mask,2) | |
# | |
net_id = ip&mask | |
broadcast = ip|broadcast | |
net_id_b = bin(net_id)[2:] | |
broadcast_b = bin(ip|broadcast)[2:] | |
# | |
# net_id = format32(net_id_b) | |
# net_broadcast = format32(broadcast_b) | |
# show8(net_id) | |
# show8(net_broadcast) | |
ts = [] | |
print "%s addrs" %(broadcast-net_id-1) | |
for x in range(net_id+1,broadcast): | |
dst = format32(bin(x)[2:]) | |
destination = show8(dst) | |
p = Ping(destination,state) | |
ts.append(p) | |
p.start() | |
for t in ts: | |
t.join() | |
for i in sorted(addrs.keys(),cmp=ip_compare): | |
print i | |
print "%d / %d addrs" %(len(addrs.keys()),broadcast-net_id-1) | |
class Ping(threading.Thread): | |
def __init__(self,ip_address,state): | |
threading.Thread.__init__(self) | |
self.ip_address = ip_address | |
self.state = state | |
def run(self): | |
result = os.popen('ping -c 1 %s' % self.ip_address).read() | |
res = re.search('1 received',result) | |
# 加锁以防止屏幕打印混乱 | |
global lock | |
lock.acquire() | |
if self.state and res: | |
addrs[self.ip_address] = '' | |
elif not self.state and not res: | |
addrs[self.ip_address] = '' | |
lock.release() | |
if __name__ == '__main__': | |
global lock | |
lock = threading.Lock() | |
main('192.168.10.0/24',state=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment