I'm writing a python program that uses Telnet to send the same few commands once every second, and then reads the output, organizes it into a Dictionary, and then prints to a JSON file (Were it is later read in by a front-end web-gui). The purpose of this is to provide a live-updates of crucial telnet command outputs.
The problem I am having is that if the connection is lost halfway though the program, it causes the program to crash. I have tried a number of ways to deal with this, such using a Boolean that is set to True once the connection is made and False if there is a timeout error, but this has some limitations. If the connection is successfully made, but later gets disconnected, the Boolean will read true in spite of the connection being lost. I have found some ways to deal with this too (Ex: if a Telnet command returns no output within 5 seconds, the connection was lost, and the boolean is updated to False).
However it is a complex program and it seems there are too many possible ways a disconnect can slip by the checks I have written and still cause the program to crash.
I am hoping to find a very simple way of checking that the Telnet command is connected. Better yet if it is a single line of code. The only way I currently know of how to check if it is connected is to try and connect again, which will fail if the network connection is lost. However, I do not want to have to open a new telnet connection every time I check to make sure it is connected. If it is already connected, it is a waste of crucial time, and there is no way to know it is not connected until after you try to connect.
I'm looking for something like:
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')
Any suggestions?
I'm running Python 2.6 (cannot update for backwards compatibility reasons)
EDIT:
This is (abridged) code of how I am presently connecting to telnet and sending/reading commands.
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
elswhere...
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]