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实现AES和RSA加解密的方法

本文实例为大家分享了python实现AES和RSA加解密的具体代码,供大家参考,具体内容如下 AES AES 是一种对称加密算法,用key对一段text加密,则用同一个key对密文解密,...

HTML中使用python屏蔽一些基本功能的方法

进行数据解析的理由不计其数,相关的工具和技巧也同样如此。但是,当您需要用这些数据做一些新的事情时,即使有“合适的”工具可能也是不够的。这一担心对于异类数据源的集成同样存在。用来做这项工作...

pytorch在fintune时将sequential中的层输出方法,以vgg为例

有时候我们在fintune时发现pytorch把许多层都集合在一个sequential里,但是我们希望能把中间层的结果引出来做下一步操作,于是我自己琢磨了一个方法,以vgg为例,有点僵硬...

Python时间戳与时间字符串互相转换实例代码

复制代码 代码如下:#设a为字符串import timea = "2011-09-28 10:00:00" #中间过程,一般都需要将字符串转化为时间数组time.strptime(a,'...

在Pytorch中使用样本权重(sample_weight)的正确方法

step: 1.将标签转换为one-hot形式。 2.将每一个one-hot标签中的1改为预设样本权重的值 即可在Pytorch中使用样本权重。 eg: 对于单个样本:loss = -...