【发布时间】:2024-01-15 01:13:01
【问题描述】:
我有一个服务器在各种端口上托管应用程序,这些端口由服务器随机分配。我希望能够扫描服务器的 IP,并找到可以用来连接这些应用程序的端口。我必须扫描超过 50K(可以是从端口 10000 到 60000 的任何地方)端口,所以我一直在寻找一种有效的方法来做到这一点。我尝试了以下方法:
import string
import time
import socket
import threading
from telnetlib import Telnet
from datetime import datetime
import nmap
def main():
""" Entry point. """
#known used ports - ['43828','38238','56272']
# Using nmap - this seems to be the only working code.
# But, with a timeout of 0.5 secs, this would take somewhere
# near 25K secs. Way too long.
# (Vast majority of ports will be closed, and timeout at a half second.
# There will only be a few dozen open ones.)
t0 = time.time()
print([testConn('10.159.122.232', x) for x in range(10000, 60000)])
t1 = time.time()
print (t1-t0)
# I found this chunk of code somewhere, using the socket lib,
# and attempting multithreading. It never completes (after 30+ min.).
r = 10000
for x in range(1,100):
t = threading.Thread(target=portscan, kwargs={'host':'10.159.122.232', 'port':r})
r += 1
t.start()
# I ripped this off of the python-nmap website, and it outputs a key error.
nm = nmap.PortScanner()
nm.scan('10.159.122.232', '38000-39000')
hosts_list = [(x, nm[x]['status']['state']) for x in nm.all_hosts()]
for host, status in hosts_list:
print(host + ' ' + status)
for port in nm['10.159.122.232']['tcp']:
thisDict = nm['10.159.122.232']['tcp'][port]
print ('Port ' + str(port) + ': ' + thisDict['product'] + ', v' + thisDict['version'])
return 0
def testConn(host, port):
""" Establish a Telnet connection and perform a login """
theSession = Telnet()
try:
theSession.open(host, port,.1)
return True
except:
return False
def portscan(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(0.2)
try:
con = s.connect((host,port))
print('Port :',port,"is open.")
con.close()
except:
pass
if __name__ == '__main__':
sys.exit(main())
有什么帮助吗??我发现的大多数线程都试图从主机扫描主机上的开放端口。我想从客户端扫描正在使用其端口的主机。这有意义吗?
谢谢!!!
【问题讨论】:
标签: python sockets networking port nmap