python - 使用python快速扫描端口
问题描述
这是我的端口扫描器代码:
from scapy.all import *
from datetime import datetime
import threading
threadlock = threading.Lock()
def TCPort(ip_addr, port):
time = 1 # max time to send packages to a port is 1 seconds
threadlock.acquire()
pkt = IP(dst=ip_addr)/TCP(dport=port,flags="S")
ans = sr1(pkt, timeout=time, verbose=0)
if(str(type(ans))=="<type 'NoneType'>"):
#port is closed
pass
elif ans.haslayer(TCP):
if (ans.getlayer(TCP).flags=="A") or (ans.getlayer(TCP).flags=="SA"):
# port sent a SYN or SYN-ACK answer, so answer with RST to close
# the connection and print the port
sr1(IP(dst=ip_addr)/TCP(dport=port,flags="S"), timeout=time, verbose=0)
print port,"open".rjust(9-len(str(port)))
threadlock.release()
#main
ip_addr = "192.168.1.33"
ports = range(1,500)
start = datetime.now()
print "Started on", start.strftime('%Y-%m-%d %H:%M:%S')
for port in ports:
t1 = threading.Thread(target=TCPort, args=(ip_addr,port))
t2 = threading.Thread(target=TCPort, args=(ip_addr,port))
t3 = threading.Thread(target=TCPort, args=(ip_addr,port))
t4 = threading.Thread(target=TCPort, args=(ip_addr,port))
t5 = threading.Thread(target=TCPort, args=(ip_addr,port))
t6 = threading.Thread(target=TCPort, args=(ip_addr,port))
t7 = threading.Thread(target=TCPort, args=(ip_addr,port))
t8 = threading.Thread(target=TCPort, args=(ip_addr,port))
t9 = threading.Thread(target=TCPort, args=(ip_addr,port))
t10 = threading.Thread(target=TCPort, args=(ip_addr,port))
t1.start()
t2.start()
t3.start()
t4.start()
t5.start()
t6.start()
t7.start()
t8.start()
t9.start()
t10.start()
t1.join()
t2.join()
t3.join()
t4.join()
t5.join()
t6.join()
t7.join()
t8.join()
t9.join()
t10.join()
print "Finished on", datetime.now()-start
而不是为线程做 10 个变量,我怎样才能用更少的行和更少的变量来做线程?
*** 此问题已编辑为更具体的问题
*** 忽略此段落。系统不让我发布编辑,因为我需要写更多的字,所以你可以忽略这一段(顺便说一句,如果你读到这个我很高兴知道我是如何绕过这个限制的)
解决方案
我会推荐一种基于池的方法,您可以在其中创建一组线程/进程,然后为它们提供您要检查的端口。 线程池类似于多处理池? 是如何用线程做到这一点,在这种情况下,这应该是你所需要的。这为您管理线程的大部分烦人部分。
推荐阅读
- oracle - How to write to job log from Oracle Report Builder 10.1.2.3.0
- reactjs - 在开玩笑测试中安装组件之前运行的 useEffect
- asp.net - Modal 上不显示按钮和输入
- javascript - 将组相对变换应用于对象
- sql-server - SSIS 日志提供程序不适用于 SQL Server 用户
- sql - Multiple occurances of the same Column variable in a query
- python - 可以在单个损失函数中使用多头 Keras 模型的不同形状的输出吗?
- visual-c++ - Assigning characters of array data members
- java - AWS EC2 / MySql - spring boot 无法从数据源确定 jdbc url
- python - HTML renders fine in browser but not in email (HTML is generated using pandas dataframe)