1、socket实现端口扫描
1 #!/usr/bin/python3
2 #-*- coding:utf-8 -*-
3
4 #编写环境 windows 7 x64 + Python3.7.0
5 #socket实现端口扫描
6
7 import socket
8 import time
9
10 def scan(ip, port):
11 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
12 try:
13 server.connect((ip,port))
14 print('{0} port {1} is open'.format(ip, port))
15 except Exception as e:
16 print('{0} port {1} is off'.format(ip,port))
17 finally:
18 server.close()
19
20 def scanport():
21
22 ip = '10.10.10.3'
23 print('{0}'.format(ip))
24 portlist = [22,443,80,21,23,3306,1433,1521,3389,5432,6379,7001]
25 #portlist = [80,443]
26 starttime = time.time()
27
28 for port in portlist:
29 scan(ip, port)
30
31 endtime = time.time()
32 print('一共运行了{0}秒'.format((endtime-starttime)))
33
34 if __name__ == '__main__':
35 scanport()
2、telnetlib实现端口扫描
1 #!/usr/bin/python3
2 #-*- coding:utf-8 -*-
3
4 #编写环境 windows 7 x64 + Python3.7.0
5 #telnetlib实现端口扫描
6
7 import telnetlib
8 import time
9
10 def scan(ip, port):
11 server = telnetlib.Telnet() # 创建一个Telnet对象
12 try:
13 server.open(ip,port) # 利用Telnet对象的open方法来创建TCP连接测试端口是否开放
14 print('{0} port {1} is open'.format(ip, port))
15 except Exception as e:
16 print('{0} port {1} is off'.format(ip,port))
17 finally:
18 server.close()
19
20 def scanport():
21
22 ip = '10.10.10.3'
23 print('{0}'.format(ip))
24 portlist = [22,443,80,21,23,3306,1433,1521,3389,5432,6379,7001]
25 #portlist = [80,443]
26 starttime = time.time()
27
28 for port in portlist:
29 scan(ip, port)
30
31 endtime = time.time()
32 print('一共运行了{0}秒'.format((endtime-starttime)))
33
34 if __name__ == '__main__':
35 scanport()
3、多线程实现端口扫描
1 #!/usr/bin/python3
2 #-*- coding:utf-8 -*-
3
4 #编写环境 windows 7 x64 + Python3.7.0
5 #telnetlib实现端口扫描
6
7 import telnetlib
8 import threading
9 import time
10
11 def scan(ip, port):
12 server = telnetlib.Telnet() # 创建一个Telnet对象
13 try:
14 server.open(ip,port) # 利用Telnet对象的open方法来创建TCP连接测试端口是否开放
15 print('{0} port {1} is open'.format(ip, port))
16 except Exception as e:
17 print('{0} port {1} is off'.format(ip,port))
18 finally:
19 server.close()
20
21 def scanport():
22
23 ip = '10.10.10.3'
24 print('{0}'.format(ip))
25 portlist = [22,443,80,21,23,3306,1433,1521,3389,5432,6379,7001]
26 #portlist = [80,443]
27 starttime = time.time()
28
29 threads = []
30 for port in portlist:
31 t = threading.Thread(target=scan,args=(ip,port))
32 t.start()
33 threads.append(t)
34
35 for t in threads:
36 t.join()
37 endtime = time.time()
38 print('一共运行了{0}秒'.format((endtime-starttime)))
39
40 if __name__ == '__main__':
41 scanport()
4、参考