1、python3实现IP地址段打印
1 #!/usr/bin/python3
2 #-*- coding:utf-8 -*-
3
4 #编写环境 windows 7 x64 + Python3.7.0
5 #python3实现IP地址段打印
6
7 #ip转换方法
8 def ip2num(ip):
9 ip=[int(x) for x in ip.split('.')]
10 return ip[0] <<24 | ip[1]<<16 | ip[2]<<8 |ip[3]
11 def num2ip(num):
12 return '%s.%s.%s.%s' %( (num & 0xff000000) >>24,
13 (num & 0x00ff0000) >>16,
14 (num & 0x0000ff00) >>8,
15 num & 0x000000ff )
16
17 #把输入的ip范围组合成一个list形式
18 def get_ip(ip):
19 start,end = [ip2num(x) for x in ip.split('-') ]
20 return [ num2ip(num) for num in range(start,end+1) if num & 0xff ]
21
22
23 if __name__ == '__main__':
24 iplist = get_ip('10.10.10.1-10.10.10.10')
25 print(iplist)
2、python3实现telnet查看IP地址段端口开放情况
1 #!/usr/bin/python3
2 #-*- coding:utf-8 -*-
3
4 #编写环境 windows 7 x64 + Python3.7.0
5 #python3实现telnet查看IP地址段端口开放情况
6
7 import telnetlib
8 import gevent
9
10 #ip转换方法
11 def ip2num(ip):
12 ip=[int(x) for x in ip.split('.')]
13 return ip[0] <<24 | ip[1]<<16 | ip[2]<<8 |ip[3]
14 def num2ip(num):
15 return '%s.%s.%s.%s' %( (num & 0xff000000) >>24,
16 (num & 0x00ff0000) >>16,
17 (num & 0x0000ff00) >>8,
18 num & 0x000000ff )
19
20 #把输入的ip范围组合成一个list形式
21 def get_ip(ip):
22 start,end = [ip2num(x) for x in ip.split('-') ]
23 return [ num2ip(num) for num in range(start,end+1) if num & 0xff ]
24
25
26 def scan(ip):
27 #调用系统的telnetlib,telnet指定ip的指定端口,如果成功,则
28 try:
29 port =22
30 server = telnetlib.Telnet(ip, port, timeout=10)
31
32 #给ip后面加一个换行符,用来在txt里面换行显示
33 new_ip = ip + '\n'
34
35 #以追加的形式将端口开放的ip列出来
36 file = open('thefile.txt', 'a')
37 file.write(new_ip)
38 file.close()
39 print('{0} port {1} is open'.format(ip, port))
40 except Exception as e:
41 print('{0} port {1} is off'.format(ip, port))
42 print(e)
43
44
45 if __name__ == '__main__':
46 iplist = get_ip('10.10.10.1-10.10.10.10')
47 print(iplist)
48
49 #单线程模式
50 # for ip in iplist:
51 # print scan(ip)
52
53
54 #协程模式,多并发
55 #下面这句的意思就是循环列表里面的ip,全部加到协程(gevent)里面,一起并发启动执行
56 threads = [gevent.spawn(scan, ip) for ip in iplist]
57 gevent.joinall(threads)
3、参考
https://blog.51cto.com/mapengfei/1926039?cid=695986