2011-11-17 50 views
2

我試圖做一個腳本,它通過telnet連接到服務器。我正在使用python和telnetlib。我有問題超時工作。我想在連接到主機時使用可選超時,以便在主機不在線時收到異常。Python的Telnetlib和連接超時

我已經閱讀了python telnetlib文檔,但我不知道我的代碼有什麼問題。

這裏是我的簡單的代碼:

import telnetlib 

host = 'hostname' 
tn = telnetlib.Telnet(host, 23, 5) # port 23, timeout 45secs 
print 'Connecting to', host 
tn.close() 

這裏是我的錯誤信息:

Exception exceptions.AttributeError: "Telnet instance has no attribute 'sock'" in  <bound method Telnet.__del__ of <telnetlib.Telnet instance at 0x7f269864b8c0>> ignored 
Traceback (most recent call last): 
File "test2.py", line 7, in <module> 
tn = telnetlib.Telnet(host, 23, 5) 
TypeError: __init__() takes at most 3 arguments (4 given) 

回答

4

你可能不使用Python 2.6或以上。從文檔引用:

在版本2.6中更改:超時已添加。

+0

就是這樣!我正在運行python 2.5.2。由於我們公司的政策,Python可能無法升級到新版本。也許我會嘗試信號:http://pguides.net/python/timeout-a-function – makarhum

+0

你也可以嘗試使用更新後的telnetlib.py:http://hg.python.org/cpython/file/2.7/ Lib/telnetlib.py - 也許你需要回溯一些東西,但它應該工作 –