I got this error when I was working on a Python script which use telnet to execute some show commands in Cisco 3650 and Cisco 2960 switches. Strangely I only got this error with Cisco 3650 (16.3.5b) switches.
[WinError 10054] An existing connection was forcibly closed by the remote host
I was in a rush to get the script working and the work around below fixed the issue.
1) The most useful method troubleshoot this was enabling debug in telnetlib
telnet = telnetlib.Telnet(ipOfRouterf)
telnet.set_debuglevel(1000)
2) Looking at the output with debugging on, it looked like that this issues is caused by the "exit" command in Cisco CLI.
cmd1 = 'show snmp location'
telnet = telnetlib.Telnet(ipOfRouterf)
telnet.set_debuglevel(1000)
telnet.read_until(b"Username: ",3)
telnet.write(user.encode('ascii') + b"\r\n")
telnet.read_until(b"Password: ",3)
telnet.write(password.encode('ascii') + b"\r\n")
telnet.write(cmd1.encode('ascii')+b"\r\n")
telnet.write(b"exit\r\n")
cmdOUT1 = telnet.read_all().decode('ascii')
print(cmdOUT1)
3) The work around I applied was to remove "exit" , enter a command that is invalid but unique so that telnet.read_until('testtest1234') can find it and then use telnet.close() instead of "exit"
cmd1 = 'show cdp neighbor'
cmd2 = 'show snmp location'
telnet = telnetlib.Telnet(ipOfRouterf,timeout = 3)
telnet.set_debuglevel(1000)
telnet.read_until(b"Username: ",3)
telnet.write(user.encode('ascii') + b"\r\n")
telnet.read_until(b"Password: ",3)
telnet.write(password.encode('ascii') + b"\r\n")
telnet.write(b"\r\n")
telnet.write(b"\r\n")
telnet.write(cmd1.encode('ascii')+b"\r\n")
telnet.write(b"\r\n")
telnet.write(cmd2.encode('ascii')+b"\r\n")
telnet.write(b"\r\n")
telnet.write(b"testtest1234\r\n")
cmdOUT1 = telnet.read_until(b"testtest1234").decode('ascii')
telnet.close()
print(cmdOUT1)
No comments:
Post a Comment