python 探测IP端口

# -*-coding:utf-8-*-
import logging
import multiprocessing
import optparse
import os
import socket
import time
from concurrent.futures.thread import ThreadPoolExecutor
from queue import Queue
from socket import *

# LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
# DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
# logging.basicConfig(filename='plumb_port.log', level=logging.DEBUG, format=LOG_FORMAT, datefmt=DATE_FORMAT)

queue = Queue()
IS_UPDATE = True


def writeFile():
    with open(time.strftime("%Y%m%d%H%M%S", time.localtime()) + 'ipPortResult.txt', 'w') as f:
        while not queue.empty():
            i = queue.get()
            f.write(i + "\n")


def main():
    #添加帮助
    optParser = optparse.OptionParser()
    optParser.add_option('-f', '--file', action='store', type='string', dest='filepath',
                         metavar='IP文件,每个ip一行,如果没有此参数,默认当前路径下ip.txt文件')
    optParser.add_option('-v', '--version', action='store', type='string', dest='version', metavar='版本')
    fakeArgs = ['-f', r'C:\Users\wk\Desktop\test\ip.txt', '-v', 'how are you', 'arg1', 'arg2']
    option, args = optParser.parse_args(fakeArgs)
    #没有给出文件地址使用默认当前文件夹内ip.txt
    if option.filepath is None:
        file_path = os.path.join(os.path.abspath('.'), 'ip.txt')
    else:
        file_path = option.filepath
    if not os.path.exists(file_path):
        # logging.error('没有此路径')
        print('没有此路径%s'%file_path)
        return
    with open(file_path, 'r') as f:
        lines = f.readlines()
        size = len(lines)
        for i in range(size):
            forIp(lines[i].strip())
            print(float((i + 1 / size) * 100), end="\r")


def forIp(ip):
    with ThreadPoolExecutor(max_workers=5000) as t:  # 创建一个最大容纳数量为2000的线程池
        for port in range(0, 65535):
            t.submit(portScan, ip, port)

#探测IP
def portScan(host, port):
    sock = socket(AF_INET, SOCK_STREAM)
    sock.settimeout(1)
    try:
        if sock.connect_ex((host, port)) == 0:#sock.connect_ex()返回0的时候表示ip端口打开
            print("[*]%s:%d open" % (host, port))
            queue.put("[*]%s:%d open" % (host, port))
    except:
        pass
    finally:
        sock.close()


if __name__ == '__main__':
    time1 = int(time.time())
    main()
    print("结束!")
    print("耗时:%d" % (int(time.time()) - time1))
    time.sleep(2)
    writeFile()

写数据也可以单起一个线程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值