Python 扫描IP段 指定端口是否开放
TCP21.py
12 | socket.setdefaulttimeout( 10 ) |
14 | class socket_port(threading.Thread): |
15 | def __init__( self ,cond, name): |
16 | super (socket_port, self ).__init__() |
24 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
25 | s.connect(( self .HOST,PORT)) |
27 | print self .HOST,u ":" ,PORT,u "端口开放" |
45 | ip = [ int (x) for x in ip.split( '.' )] |
46 | return ip[ 0 ]<< 24 | ip[ 1 ]<< 16 | ip[ 2 ]<< 8 | ip[ 3 ] |
58 | return '%s.%s.%s.%s' % ( (num & 0xff000000 ) >> 24 , |
59 | (num & 0x00ff0000 ) >> 16 , |
60 | (num & 0x0000ff00 ) >> 8 , |
69 | return [num2ip(num) for num in range (ip1,ip2 + 1 ) if num & 0xff ] |
72 | if __name__ = = '__main__' : |
74 | list_ip = gen_ip(ip2num(ini.IP1),ip2num(ini.IP2)) |
78 | while I1 < len (list_ip): |
81 | cond = threading.Event() |
82 | hider = socket_port(cond,list_ip[I1]) |
85 | ini.ini_write(list_ip[I1],ini.IP2) |
ini.py
20 | config = ConfigParser.ConfigParser() |
21 | config.readfp( open (INITXT)) |
22 | IP1 = config.get( "ipdata" , "ip1" ) |
23 | IP2 = config.get( "ipdata" , "ip2" ) |
31 | config = ConfigParser.ConfigParser() |
32 | config.add_section( "ipdata" ) |
33 | config. set ( "ipdata" , "ip1" ,ip1) |
34 | config. set ( "ipdata" , "ip2" ,ip2) |
35 | config.write( open (INITXT, "w" )) |
39 | def ini_write(ip1,ip2): |
42 | config = ConfigParser.ConfigParser() |
44 | if not config.has_section( "ipdata" ): |
45 | temp = config.add_section("") |
46 | config. set ( "ipdata" , "ip1" ,ip1) |
47 | config. set ( "ipdata" , "ip2" ,ip2) |
48 | config.write( open (INITXT, "r+" )) |
运行
转自:
http://www.sharejs.com/codes/python/5338
利用了里面的两个函数
def ip2num(ip):
ip = [int(x) for x in ip.split('.')]
46
return ip[0]<<24 | ip[1]<<16 | ip[2]<<8 | ip[3]
def num2ip(num):
return '%s.%s.%s.%s' % ( (num & 0xff000000) >> 24,
(num & 0x00ff0000) >> 16,
(num & 0x0000ff00) >> 8,
num & 0x000000ff )
其它地方没仔细验证