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可视化mhd格式和raw格式的医学图像并保存的方法

Python可视化mhd格式和raw格式的医学图像并保存的方法

mhd格式的文件里面包含的是raw图像的一些头信息,比如图片大小,拍摄日期等等,那么如何可视化图像呢? import cv2 import SimpleITK as sitk imp...

Python 3.x 判断 dict 是否包含某键值的实例讲解

查询资料得 Python 可以使用两种方式判断字典是否包含某键值 1、(dict.has_key('keyname')) 2、('keyname' in dict) 觉得第二种方式太过丑...

Python with用法:自动关闭文件进程

实际上,Python 提供了 with 语句来管理资源关闭。比如可以把打开的文件放在 with 语句中,这样 with 语句就会帮我们自动关闭文件。 with 语句的语法格式如下:...

Python函数中*args和**kwargs来传递变长参数的用法

单星号形式(*args)用来传递非命名键可变参数列表。双星号形式(**kwargs)用来传递键值可变参数列表。 下面的例子,传递了一个固定位置参数和两个变长参数。 def test_...

整理Python最基本的操作字典的方法

Python 中的字典是Python中一个键值映射的数据结构,下面介绍一下如何优雅的操作字典. 1.1 创建字典 Python有两种方法可以创建字典,第一种是使用花括号,另一种是使用内建...