2016-03-21 111 views
-1

我剛剛開始學習python編程,並且一直在學習關於編程套接字的教程,以創建一個簡單的端口掃描器。當我手動輸入所有代碼進行一次迭代時,我能夠成功連接到本地主機,但是如果我使用相同的代碼,並在利用try/except的for循環中應用它,我會立即爲每個端口獲取異常在這個範圍內,即使我知道有些港口是開放的。我相信我已經將問題隔離到了socket.connect(),因爲我已經輸入了下面的代碼,我知道它永遠不會被執行。一旦爲什麼在Python 3.4的循環中使用socket.connect()時會停止工作?

b'SSH-2.0-OpenSSH_6.2\r\n' 

Process finished with exit code 0 

然而,正如我之前的代碼,並將其移動到與循環:

我可以輸入以下代碼,並得到成功的回報:

import socket 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.settimeout(10) 
port = 22 
s.connect(('127.0.0.1', port)) 
s.send(b'test') 
banner = s.recv(1024) 
print(banner) 
s.close() 

回報端口號作爲迭代器,它停止工作。

import socket 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.settimeout(10) 
for port in range(1,26): 
    print("[+]Attempting to connect to : " + str(port)) 
    try: 
     s.connect(('127.0.0.1', port)) 
     s.send(b'test') 
     banner = s.recv(1024) 
     s.close() 
     if banner: 
     print("Port " + port + "is Open: " + banner) 
    except: print("[+]Port " + str(port) + " is closed") 

回報:

[+]Attempting to connect to : 1 
[+]Port 1 is closed 
[+]Attempting to connect to : 2 
[+]Port 2 is closed 
[+]Attempting to connect to : 3 
[+]Port 3 is closed 
....ETC....ETC....ETC.... 
[+]Attempting to connect to : 24 
[+]Port 24 is closed 
[+]Attempting to connect to : 25 
[+]Port 25 is closed 

即使我知道22端口是開放的,監聽本地主機。 (即我可以沒有問題地ssh到127.0.0.1)。我嘗試了所有我能想到的無用功,包括通過使用內部int()函數手動更改端口的數據類型爲int,我試過了socket.connect_ex對象等。我也把代碼就在socket.connect語句下面,看看它是否顯示出來,它從來沒有做過。

+3

打印實際的錯誤,不要補一個。什麼是提出的實際例外?我猜想,因爲你關閉了套接字,所以你不能重用它。爲每個連接嘗試創建一個新的套接字對象。 – dsh

回答

3

The Zen of Python狀態:

的錯誤不應該無聲地傳遞。
除非明確沉默。

只有你沒有沉默的錯誤,而是隻用一條消息,非描述的究竟發生了什麼替代它:

>>> "Port" + 1 
Traceback (most recent call last): 
    File "<pyshell#15>", line 1, in <module> 
    "Port "+1 
TypeError: Can't convert 'int' object to str implicitly 

是你會得到什麼,如果打開端口1的工作,但您關閉套接字後,您無法連接到任何東西:

>>> a = socket.socket() 
>>> a.close() 
>>> a.connect(("www.python.com",80)) 
Traceback (most recent call last): 
    File "<pyshell#18>", line 1, in <module> 
    a.connect(("www.python.com",80)) 
OSError: [Errno 9] Bad file descriptor 

所以,你需要創建循環內一個新的socket爲它正常工作,但最重要的是:你需要限制電子rrors你抓到:

try: 
    #if this is the only line you expect to fail, then it is the only line in the try 
    s.connect(('127.0.0.1', port)) 
except ConnectionError: 
    #if a ConnectionError is the only one you expect, it is the only one you catch 
    print("[+]Port " + str(port) + " is closed") 
else: #if there was no error 
    s.send(b'test') 
    banner = s.recv(1024) 
    s.close() 
    if banner: 
     print("Port " + port + "is Open: " + banner) 

然後你會看到你所得到的,而不是猜測出了什麼問題,這也是對The Zen of Python實際的錯誤:

在不確定性面前,拒絕誘惑猜測。

+1

感謝您的澄清和糾正。這正是我的問題。 – bdubz0r

相關問題