# -*-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()
写数据也可以单起一个线程