我找到了这个Python脚本,要求输入主机名/ IP,并扫描端口1至65535以查看它们是否打开。它还使用多线程来加快过程。我遇到的两个问题是,首先,在运行时,我收到一条错误消息,指出无法创建新线程,但是在发生错误之后,将继续扫描端口并报告其状态。第二个问题是,即使某些端口(例如端口80)处于打开状态,所有端口也会恢复为关闭状态。此外,脚本在扫描到端口894后也会终止。
我尝试使用this solution,但仅导致以下错误:
TypeError: '<' not supported between instances of 'Thread' and 'int'
。至于端口状态输出,我对运行扫描的相应try语句所做的任何更改都会导致我的代码内出现错误。
下面是脚本:
from threading import *
def connect_to_host(host, port):
lock_object = Semaphore(value=1)
try:
sckt = socket(AF_INET, SOCK_STREAM)
sckt.connect((host, port))
sckt.send('Hello\r\n')
results = sckt.recv(100)
lock_object.acquire()
print('Port %d open' % port)
print(str(results))
except:
lock_object.acquire()
print('Port %d closed' % port)
finally:
lock_object.release()
sckt.close()
def scan_ports(host, ports):
try:
tgtIP = gethostbyname(host)
except:
print("Could not resolve host:'%s'" % host)
return
try:
tgtName = gethostbyaddr(tgtIP)
print('\nScanning: ' + tgtName[0])
except:
print('\n Scanning: ' + tgtIP)
setdefaulttimeout(1)
for port in ports:
t = Thread(target=connect_to_host, args=(host, int(port)))
t.start()
def main():
ports = range(1, 65535)
ports = map(str, ports)
machine = input("Please enter machine name/IP: ")
scan_ports(machine, ports)
if __name__ == '__main__':
main()
我在运行时收到的错误如下:
File "C:/Users/user123/PycharmProjects/Scripts/HS_Port_Scanner.py", line 48, in <module>
main()
File "C:/Users/user123/PycharmProjects/Scripts/HS_Port_Scanner.py", line 44, in main
scan_ports(machine, ports)
File "C:/Users/user123/PycharmProjects/Scripts/HS_Port_Scanner.py", line 37, in scan_ports
t.start()
File "C:\Users\user123\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 846, in start
_start_new_thread(self._bootstrap, ())
RuntimeError: can't start new thread
我需要帮助限制所创建线程的数量,因为脚本似乎试图创建超出系统处理能力的线程。这样一来,我在运行时不会收到上述错误。
其次,我如何才能使脚本进行适当的报告,以便该脚本列出该范围内所有端口的状态,并且不会将已知的打开端口显示为已关闭。因此,它将在端口1到端口65535(打开或关闭)上报告,并使用已知的打开端口(例如端口80)报告为打开和未关闭。