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()
相关推荐
farewellpoem 2020-11-09
lhtzbj 2020-08-13
learnpy 2020-07-19
kyelu 2020-07-09
举 2020-06-14
haokele 2020-05-31
fengling 2020-05-31
maimang00 2020-05-30
坚持是一种品质 2020-05-28
laityc 2020-05-27
jling 2020-05-19
YENCSDN 2020-05-14
singer 2020-04-30
举 2020-04-29
学习备忘录 2020-04-20
CloudXli 2020-04-07
chunjiekid 2020-08-16
小菜鸟的代码世界 2020-06-17
bizercsdn 2020-06-06