我有一个程序可以扫描远程主机上的开放端口。完成扫描需要很长时间。我想让它快一点。
下面是我的代码:
端口扫描
import socket
import subprocess
host = input("Enter a remote host to scan: ")
hostIP = socket.gethostbyname(host)
print("Please wait, scanning remote host", hostIP)
try:
for port in range(1,1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((hostIP, port))
if result == 0:
print("Port: \t Open".format(port))
sock.close()
你们这些Python巫师能帮我一下吗?提前谢谢。
发布于 2015-08-23 03:32:25
这个程序变得太简单了。它一次只监视一个端口,并且在一个端口上需要很长时间才能查看它是否正在侦听。因此,尝试减少侦听时间,如果它无法连接,则通过在run()中的"expect:“下为该数字设置递归限制,将其视为关闭。
就像这样,
try:
# connect to the given host:port
result = sock.connect_ex((hostIP, port))
if result == 0:
print "%s:%d Open" % (hostIP, port)
sock.close()
except: #pass
sock.recurse += 1
if sock.recurse < sock.limit:
sock.run()
else:
print "%s:%d Closed" % (hostIP, port)
还有其他方法可以通过导入threading()模块来提高效率,该模块可用于一次监视大量套接字。
这是关于线程的文档。
参考这个,https://docs.python.org/2/library/threading.html#
希望这对你有帮助。万事如意。
https://stackoverflow.com/questions/32159974
复制相似问题