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

yipeiwu_com5年前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路径拼接os.path.join()函数的用法

os.path.join()函数:连接两个或更多的路径名组件 1.如果各组件名首字母不包含'/',则函数会自动加上 demo1 import os Path1 = 'home'...

Python编程中运用闭包时所需要注意的一些地方

写下这篇博客,起源于Tornado邮件群组的这个问题how to use outer variable in inner method,这里面老外的回答很有参考价值,关键点基本都说到了。...

Python编程实现使用线性回归预测数据

Python编程实现使用线性回归预测数据

本文中,我们将进行大量的编程——但在这之前,我们先介绍一下我们今天要解决的实例问题。 1) 预测房子价格 房价大概是我们中国每一个普通老百姓比较关心的问题,最近几年保障啊,小编这点微末...

Python实现接受任意个数参数的函数方法

这个功能倒也不是我多么急需的功能,只是恰好看到了,觉得或许以后会用的到。功能就是实现函数能够接受不同数目的参数。 其实,在C语言中这个功能是熟悉的,虽说实现的形式不太一样。C语言中的ma...

用Python去除图像的黑色或白色背景实例

用Python去除图像的黑色或白色背景实例

用Python去除背景,得到有效的图像 此目的是为了放入深度学习计算中来减少计算量,同时突出特征,原图像为下图,命名为1.jpg,在此去除白色背景,黑色背景同理 需要对原图像进行的处理...