簡體   English   中英

程序無法處理錯誤

[英]Program is unable to handle Errors

  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()

我得到的當前輸出(當 etering 無效主機時):

輸出端

您沒有處理錯誤! 您的錯誤發生在這一行。 不在 try except 塊內

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM