2

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]
Brian C
  • 1,333
  • 3
  • 19
  • 36
  • 5
    I'd suggest that you not shell out to Telnet and instead create a socket connection from within Python. – David Hoelzer Feb 11 '16 at 01:10
  • Turn on the `keepalive` feature of the socket, and/or `send ayt` (are you there). – John Mee Feb 11 '16 at 06:27
  • @DavidHoelzer. I am not shelling out to Telnet, please see the the updated post that details how I am currently interacting with Telnet. Also, I'm not sure how to utilize a socket connection from within Python. I looked over the pyDocs but not sure how to implement it with Telent. – Brian C Feb 11 '16 at 18:56

1 Answers1

2

You can try following code to check if telnet connection is still usable or not.

    def is_connected(self):
        try:
            self.tn.read_very_eager()
            return True
        except EOFError:
            print("EOFerror: telnet connection is closed")
            return False

You can also refer https://docs.python.org/3/library/telnetlib.html for Telnet.read_very_eager() usage and:

https://lgfang.github.io/computer/2007/07/06/py-telnetlib#:~:text=The%20difference%20is%20that%20read_eager,read%20as%20much%20as%20possible.&text=The%20remaining%20read%20functions%20basically%20block%20until%20they%20received%20designated%20data.