Python实现的端口扫描功能示例

时间:2022-11-25 15:37:15

本文实例讲述了Python实现的端口扫描功能。分享给大家供大家参考,具体如下:

一 代码

?
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
import sys
import socket
import multiprocessing
def ports(ports_service):
  #获取常用端口对应的服务名称
  for port in list(range(1,100))+[143,145,113,443,445,3389, 8080]:
    try:
      ports_service[port] = socket.getservbyport(port)
    except socket.error:
      pass
def ports_scan(HOST, ports_service):
  ports_open = []
  try:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #sock.settimeout(60)
  except socket.error:
    print('socket creation error')
    sys.exit()
  for port in ports_service:
    try:
      #尝试连接指定端口
      sock.connect((HOST,port))
      #记录打开的端口
      ports_open.append(port)
      sock.close()
    except socket.error:
      pass
  return ports_open
if __name__=='__main__':
  m = multiprocessing.Manager()
  ports_service = dict()
  results = dict()
  ports(ports_service)
  #创建进程池,允许最多8个进程同时运行
  pool = multiprocessing.Pool(processes=8)
  net = '192.168.0.'
  for host_number in map(str,range(105,106)):
    host = net+host_number
    #创建一个新进程,同时记录其运行结果
    results[host] = pool.apply_async(ports_scan, (host, ports_service))
    print('starting '+host+'...')
  #关闭进程池,close()必须在join()之前调用
  pool.close()
  #等待进程池中的进程全部执行结束
  pool.join()
  #打印输出结果
  for host in results:
    print('='*30)
    print(host,'.'*10)
    for port in results[host].get():
      print(port, ':', ports_service[port])

二 运行结果

starting 192.168.0.105...
==============================
192.168.0.105 ..........
80 : http

希望本文所述对大家Python程序设计有所帮助。

原文链接:https://blog.csdn.net/chengqiuming/article/details/78601148