如何循环端口进行扫描



我有一个端口扫描仪的问题,它一直挂在扫描端口1上。我该如何解决这个问题?

#! /usr/bin/env python
import socket 
import subprocess
from datetime import datetime
#Clear the screen
subprocess.call('clear', shell=True)
def portscan():
server = raw_input("Enter the server to scan: ")
serverIP = socket.gethostbyname(server)
# Printing banner with information about host
print "[+] Host: {} [+]nIP Address: {}n".format(server, serverIP)
print "[!] Please wait, scanning for open services...n"
#Time when scan started.
t1 = datetime.now()
try:
for port in range(1, 1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((serverIP, port))
if result == 0:
print "[+] Port {}: Status:OPENn".format(result)
sock.close()
except socket.gaierror:
print "Hostname could not be resolved, Exiting...n"
sys.exit()
except socket.error:
print "Couldn't connect to server, Exitingn"
sys.exit()
#Checking time again
t2 = datetime.now()
#Calculate duration of scan
totaltime = t2 - t1
print "Scan completed, duration: {}n".format(totaltime)  

运行它时会发生什么?我给它一个主机名并将其解析为IP地址,但每当扫描开始时,它都会像我看到的那样一直扫描端口1在Wireshark 中

我认为您可能需要一个timeout

最终,您的sock.connect_ex( )将引发一个异常socket.error: [Errno 110] Connection timed out,正如您可以在这个答案中阅读到的那样。

但默认的超时时间可能是120秒,也许你不想等那么久。所以,你可以设置自己的超时,比如:

try:
for port in range(1, 1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10) #timeout set for wait up 10 seconds.
result = sock.connect_ex((serverIP, port))
sock.settimeout(None)

要了解为什么使用sock.settimeout(None),并了解设置timeout的其他方法,您可以阅读本讨论。

我不确定这是否是你想要的,但我希望它能有所帮助。

相关内容

  • 没有找到相关文章

最新更新