2017-05-28 75 views
1

我正在製作一個端口掃描器,用於檢查端口是否打開或關閉,但我確信它不起作用,因爲它將每個端口都列爲關閉狀態,即使是我專門打開的端口來檢查端口是否正常工作。任何人都可以看到我的代碼有什麼問題?如何判斷我的端口掃描器是否正常工作?

if userChoice == "1": 
    # code for option 1 
    print("You selected Port Scan Tool") 
    loop = 0 
    subprocess.call('cls', shell=True) 
    remoteServer = input("Enter a remote host to scan: ") 
    start=input("Enter starting port number: ") 
    start = int(start) 
    end=input("Enter ending port number: ") 
    end = int(end) 
    remoteServerIP = socket.gethostbyname(remoteServer) 

    # Print a nice banner with information 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() 
    timestr = time.strftime("%d.%m.%Y-%H.%M.%S")# creates time stamp on text file 

    try: 
     textFileLocation = timestr + " - Port Scan Results.txt"# creates and names text file 
     for port in range(start, end): # lets user select range 
      sock = (socket.socket(socket.AF_INET, socket.SOCK_STREAM)) 
      result = sock.connect_ex((remoteServerIP, port)) 
      if result == 0: 
       print("Port {}: \t Open".format(port)) 
       #print("Port {}: \t Closed".format(port)) 
       #print("Port {} \t Closed".format(port)) 
       textFileLocation = timestr + " - Port Scan Results.txt" 
       textFile = open(textFileLocation, "a") 
       textToWrite = "Open: Port %d\n" % port 
       textFile.write(textToWrite) 
       textFile.close() 
      else: 
       print("Port {}: \t Closed".format(port)) 
       textFileLocation = timestr + " - Port Scan Results.txt" 
       textFile = open(textFileLocation, "a") 
       textToWrite = "Closed: Port %d\n" % port 
       textFile.write(textToWrite) 
       textFile.close() 
      sock.close() 
+0

在將它放入循環之前測試了套接字函數嗎?另外,你應該真的在循環之前打開輸出文件 –

+0

@ cricket_007它不僅僅是open()在錯誤的地方。這段代碼是,我不知道它是什麼。令人震驚的越野車或一些類似的表達會我想。 – Dalen

回答

2

這隻測試是否有任何程序在所述端口上偵聽。

要查看它是否有效,請首先刪除try塊以查看返回的錯誤。然後在異常處理中使用正確的錯誤,即如果您的機器不在網絡上,那麼嘗試將失敗以及無法連接。 此外,您將不得不引入超時,以便套接字不會掛起嘗試連接。

要查看您的代碼是否正在對目標計算機執行任何操作,請在該處啓動防火牆並將其設置爲通知您是否有人正在執行您所做的操作。如果您的路由器/切換器阻止網絡上的端口掃描,您的代碼也可能會失敗。你也應該檢查它的防火牆設置。

您也錯過了代碼中的except代碼塊,嘗試錯誤的地方。 你必須測試每個連接:

for x in range(...): 
    try: 
     s = socket.socket(...) 
     s.connect(...) 
     s.close() 
    except: pass 

雖然你應該使用例如:

except socket.SocketError as error: 

,然後檢查其中的異常將被存儲的錯誤數等變量的錯誤。

哦,順便說一句,socket.socket.connect()返回None,所以你的檢查總是False。 這不是C,它的Python。

>>> ... 
>>> result = sock.connect(...) 
>>> print result 
None 

嘗試除了會告訴你,連接是否通過或失敗了很多更多的信息。

+0

很好的答案,但真正的問題是「所以你的支票永遠是假的。」 –