Python多线程端口扫描工具实现详解

Mason
Mason
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍基于Python实现的多线程端口扫描功能。通过多线程技术提升扫描效率,支持单IP和多IP批量扫描模式。代码包含端口范围校验、超时设置及连接状态检测,适用于快速检测主机开放端口,为网络管理员提供实用的安全评估工具。

本文详细介绍如何利用Python编写一个多线程端口扫描程序,旨在为读者提供一份可直接参考和使用的代码示例。

以下代码展示了如何针对指定IP地址执行多线程端口扫描的具体实现逻辑。

#!/usr/bin/env python
#encoding: utf-8
import socket, sys, thread, time
openPortNum = 0
socket.setdefaulttimeout(3)
def usage():
  print '''''Usage:
  Scan the port of one IP: python port_scan_multithread.py -o <ip>
  Scan the port of one IP: python port_scan_multithread.py -m <ip1, ip2, ip3, ip4 ...>
  '''
  print 'Exit'
  sys.exit(1)
def socket_port(ip, PORT):
  global openPortNum
  if PORT > 65535:
    print 'Port scanning beyond the port range, interrupt to scan'
    sys.exit(1)
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  result = s.connect_ex((ip, PORT))
  if(result == 0):
    print ip, PORT,'is open'
    openPortNum += 1
  s.close()
def start_scan(IP):
  for port in range(0, 65535+1):
    thread.start_new_thread(socket_port, (IP, int(port)))
    time.sleep(0.006)
if __name__ == '__main__':
  t = 0
  if len(sys.argv)<2 or sys.argv[1] == '-h':
    usage()
  elif sys.argv[1] == '-o':
    ONE_IP = raw_input('Please input ip of scanning: ')
    t = time.time()
    start_scan(ONE_IP)
  elif sys.argv[1] == '-m':
    MANY_IP = raw_input('Please input many ip of scanning: ')
    IP_SEG = MANY_IP.split(',')
    t = time.time()
    for i in IP_SEG:
      start_scan(i)
  print
  print 'total open port is %s, scan used time is: %f ' % (openPortNum, time.time()-t)

程序运行时的实际输出效果如下图所示。

若需深入了解Python其他相关技巧,建议参阅本站专题:《Python URL操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》以及《Python文件与目录操作技巧汇总》。

期望上述内容能对您的Python编程实践提供有效帮助。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表