python多线程扫描端口(线程池)

yipeiwu_com6年前Python基础

扫描服务器ip开放端口,用线程池ThreadPoolExecutor,i7的cpu可以开到600个左右现成,大概20s左右扫描完65535个端口,根据电脑配置适当降低线程数

#!/usr/local/python3.6.3/bin/python3.6
# coding = utf-8

import socket
import datetime
import re
from concurrent.futures import ThreadPoolExecutor, wait

DEBUG = False

# 判断ip地址输入是否符合规范
def check_ip(ipAddr):
  compile_ip = re.compile('^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$')
  if compile_ip.match(ipAddr):
    return True
  else:
    return False

# 扫描端口程序
def portscan(ip, port):
  try:
    s = socket.socket()
    s.settimeout(0.2)
    s.connect((ip, port))
    openstr = f'[+] {ip} port:{port} open'
    print(openstr)
  except Exception as e:
    if DEBUG is True:
      print(ip + str(port) + str(e))
    else:
      return f'[+] {ip} port:{port} error'
  finally:
    s.close

#主程序,利用ThreadPoolExecutor创建600个线程同时扫描端口
def main():
  while True:
    ip = input("请输入ip地址:")
    if check_ip(ip):
      start_time = datetime.datetime.now()
      executor = ThreadPoolExecutor(max_workers=600)
      t = [executor.submit(portscan, ip, n) for n in range(1, 65536)]
      if wait(t, return_when='ALL_COMPLETED'):
        end_time = datetime.datetime.now()
        print("扫描完成,用时:", (end_time - start_time).seconds)
        break


if __name__ == '__main__':
  main()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python占用的内存优化教程

概述 如果程序处理的数据比较多、比较复杂,那么在程序运行的时候,会占用大量的内存,当内存占用到达一定的数值,程序就有可能被操作系统终止,特别是在限制程序所使用的内存大小的场景,更容易发...

Python使用htpasswd实现基本认证授权的例子

Python使用htpasswd实现基本认证授权的例子

前面我讲解了如何将树莓派(Raspberry Pi)打造成无线路由,感觉每次通过命令ssh管理显麻烦,于是自己动手编写Web界面,主要是使用Python编写的CGI程序,这里用到了min...

python实现12306火车票查询器

python实现12306火车票查询器

12306火车票购票软件大家都用过,怎么用Python写一个命令行的火车票查看器,要求在命令行敲一行命令来获得你想要的火车票信息,下面通过本文学习吧。 Python火车票查询器 接口...

使用urllib库的urlretrieve()方法下载网络文件到本地的方法

使用urllib库的urlretrieve()方法下载网络文件到本地的方法

概述 见源码 源码 # !/usr/bin/env python # -*- coding:utf-8 -*- """ 图片(文件)下载,核心方法是 urllib.urlre...

Python是编译运行的验证方法

虽然Python被说成是一种解释型语言,但是实际上,Python源程序要先经过编译,然后才能运行。 与Java语言类似,Python源程序编译之后得到的是字节码,交由Python虚拟机来...