程序无法处理错误


  1. 这是一个快速主机端口扫描器的源代码…我添加了一些错误处理……但是程序无法读取错误处理内容,当主机无效时,它只是给出正常的python错误…我哪里说错了?

  2. 我如何打印这个程序的输出到一个文本文件?)我最后试了一下,但没有用。

感谢任何帮助!

源代码:

#!/usr/bin/env python
import socket
import concurrent.futures
import subprocess
import sys
from datetime import datetime

# Clear the screen
subprocess.call('clear', shell=True)
# Ask for input
remoteServer = input("Enter a remote host to scan: ")
remoteServerIP  = socket.gethostbyname(remoteServer)
# Prints a banner with info on which host we are about to scan
print ("-" * 60)
print ("Please wait, scanning remote host", remoteServerIP)
print ("-" * 60)
# Check what time the scan started
t1 = datetime.now()
def scan(remoteServerIP, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)

try:
remoteServerIP  = socket.gethostbyname(remoteServer)
result = sock.connect_ex((remoteServerIP, port))        
if result == 0:
print ("Port {}:      Open".format(port))
sock.close()

# We have also put in error handling for catching errors
except KeyboardInterrupt:
print ("You pressed Ctrl+C")
sys.exit()
except socket.gaierror:
print ('Hostname could not be resolved. Exiting')
sys.exit()
except socket.error:
print ("Host is not available",)
sys.exit()
with concurrent.futures.ThreadPoolExecutor(max_workers=75) as executor:
for port in range(1,1025):
executor.submit(scan, remoteServerIP, port + 1)
# Checking the time again
t2 = datetime.now()
# Calculates the difference of time, to see how long it took to run the script
total =  t2 - t1
# Printing the information to screen
print ('Scanning Completed in: ', total)
#Text file
f = open('Hostreport.txt', 'a')
print(port,file=f)
f.close()

当前输出(当指定无效主机时):

输出党卫军

您没有处理错误!你的错误发生在这一行。不在try except块

# Ask for input
remoteServer = input("Enter a remote host to scan: ")
remoteServerIP  = socket.gethostbyname(remoteServer)  # this one.