0

I am trying to the device status connected to my desktop via switch using telnetlib. The following is the code which I am using in which recursively first I am checking whether the ping to the device IP address is ok or not and then check the device status using telnet connection:

import telnetlib
import os
import time
import datetime

def chk_telnet(ip_addr):
    try:
        tn = telnetlib.Telnet(ip_addr)

        tn.write(b"DSP ST ML\r\n")
        time.sleep(3)

        tn.write(b"exit\n")

        output =  tn.read_until(b"exit")
        time.sleep(3)

        tn.close()

        output_str = output.decode('utf-8')

        if "ML ALARMS = NONE" in output_str:
            print(str(datetime.datetime.now()) + ' ' + " DEVICE UP\n")

        elif ("ML ALARMS = LOCAL SYNC LOSS" in output_str):
            print(str(datetime.datetime.now()) + ' ' + " DEVICE DOWN\n")

        elif ("ML ALARMS = REMOTE SYNC LOSS" in output_str):
            print(str(datetime.datetime.now()) + ' ' + " DEVICE DOWN\n")
            
    except ConnectionRefusedError:
        return

def chk_ping(host_addr):

     host_addr_status = os.system("ping -n 1 " + host_addr)

     if (host_addr_status == 0):
         chk_telnet(host_addr)

     else:
         print(str(datetime.datetime.now()) + ' ' + " DEVICE IS OFFLINE CHECK SWITCH CONNECTION\n")

     chk_ping(host_addr)

chk_ping('192.168.x.x')

The above code runs fine and displays the status of the device correctly if the connection to the device via switch is ok (or to say the ping is ok). But if the switch connection is removed for sometime and restored back in middle of the program (one of the test cases) then connection to the device via telnetlib is not getting established.

After restoration of the switch connection (or ping becomes ok), when I tried to the debug the issue using print(output_str), it displayed Tenet session is already occupied by another user and subsequently the above program does nothing.

Can someone suggest how to resolve this issue.

RRSC
  • 257
  • 2
  • 15
  • When the connection is interrupted, does the connected process exit, or is it still in the `read_until` process? – Tim Roberts Sep 10 '22 at 03:34
  • Hi @TimRoberts. The connection is still in the ```read_until``` process. – RRSC Sep 10 '22 at 03:46
  • That's the documented behavior. Perhaps you need to use a timeout, and retry until you get the data or get an `EOFError`, indicating connection lost. – Tim Roberts Sep 10 '22 at 04:52
  • @TimRoberts your suggestion helped me after I had included timeout logic in my program. But now I landed up in max. recursive depth issue since the function is calling itself iteratively. How to resolve this can you suggest. – RRSC Sep 19 '22 at 13:00
  • Why on earth are you doing this recursively? Use a `while True:` loop. – Tim Roberts Sep 19 '22 at 17:15

0 Answers0