[英]Using Python to check if Telnet is still connected
我正在編寫一個 python 程序,它使用 Telnet 每秒發送一次相同的幾個命令,然后讀取輸出,將其組織成一個字典,然后打印到一個 JSON 文件(后來被前端讀入 -結束 web-gui)。 這樣做的目的是提供關鍵 telnet 命令輸出的實時更新。
我遇到的問題是,如果連接在程序中途丟失,則會導致程序崩潰。 我嘗試了多種方法來解決這個問題,例如使用一個布爾值,一旦建立連接就設置為 True,如果出現超時錯誤,則設置為 False,但這有一些限制。 如果連接成功,但后來斷開連接,盡管連接丟失,布爾值仍將讀取為真。 我也找到了一些方法來解決這個問題(例如:如果 Telnet 命令在 5 秒內沒有返回任何輸出,則連接丟失,布爾值更新為 False)。
然而,它是一個復雜的程序,似乎有太多可能的方式斷開連接可能會被我編寫的檢查忽略並仍然導致程序崩潰。
我希望找到一種非常簡單的方法來檢查 Telnet 命令是否已連接。 如果它是一行代碼,那就更好了。 我目前知道如何檢查它是否已連接的唯一方法是再次嘗試連接,如果網絡連接丟失,這將失敗。 但是,我不想每次檢查以確保它已連接時都必須打開新的 telnet 連接。 如果它已經連接,那是浪費關鍵時間,並且在您嘗試連接之前無法知道它是否連接。
我正在尋找類似的東西:
tnStatus = [function or line of code that checks if Telnet is connected (w/o trying to open a connection), and returns boolean]
if(tnStatus == True):
sendComand('bla')
有什么建議?
我正在運行 Python 2.6(由於向后兼容性原因無法更新)
編輯:
這是我目前如何連接到 telnet 和發送/讀取命令的(刪節)代碼。
class cliManager():
'''
Class to manage a Command Line Interface connection via Telnet
'''
def __init__(self, host, port, timeout):
self.host = host
self.port = port
self.timeout = timeout #Timeout for connecting to telnet
self.isConnected = False
# CONNECT to device via TELNET, catch connection errors.
def connect(self):
try:
if self.tn:
self.tn.close()
print("Connecting...")
self.tn = telnetlib.Telnet(self.host, self.port, self.timeout)
print("Connection Establised")
self.isConnected = True
except Exception:
print("Connection Failed")
self.isConnected = False
.
.
.
def sendCmd(self, cmd):
# CHECK if connected, if not then reconnect
output = {}
if not self.reconnect():
return output
#Ensure cmd is valid, strip out \r\t\n, etc
cmd = self.validateCmd(cmd)
#Send Command and newline
self.tn.write(cmd + "\n")
response = ''
try:
response = self.tn.read_until('\n*', 5)
if len(response) == 0:
print "No data returned!"
self.isConnected = False
except EOFError:
print "Telnet Not Connected!"
self.isConnected = False
output = self.parseCmdStatus(response)
return output
其他地方...
cli = cliManager("136.185.10.44", 6000, 2)
cli.connect()
giDict = cli.sendCmd('getInfo')
[then giDict and other command results go to other methods where they are formatted and interpreted for the front end user]
您可以嘗試以下代碼來檢查 telnet 連接是否仍然可用。
def is_connected(self):
try:
self.tn.read_very_eager()
return True
except EOFError:
print("EOFerror: telnet connection is closed")
return False
您還可以參考https://docs.python.org/3/library/telnetlib.html了解 Telnet.read_very_eager() 用法和:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.