【发布时间】:2016-05-21 14:56:28
【问题描述】:
我正在编写一个 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,而是从 Python 中创建套接字连接。
-
打开套接字的
keepalive功能,和/或send ayt(你在吗)。 -
@DavidHoelzer。我不是在使用 Telnet,请参阅更新后的帖子,详细说明我目前如何与 Telnet 交互。另外,我不确定如何在 Python 中使用套接字连接。我查看了 pyDocs,但不确定如何用 Telent 实现它。
标签: python networking telnet telnetlib