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.