cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
2155
Views
0
Helpful
5
Replies

SG500 Swith Python Telnet Script error

JCubio
Level 1
Level 1

Hi All,

I'm trying to connect to our switch via telnet using script. It's just a basic script to change the hostname. But everytime I run the scrip I get an error.

 

import getpass
import telnetlib

HOST='192.168.0.2'
user = input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until(b"Username: ")
tn.write(user.encode('ascii') + b"\n")
if password:
    tn.read_until(b"Password: ")
    tn.write(password.encode('ascii') + b"\n")

    tn.write(b"conf t\n")
    tn.write(b"hostname SW-Core1\n")
    tn.write(b"exit\n")
    tn.write(b"write\n")
        

    print(tn.read_all().decode('ascii'))

But everytime I run the scrip I get an error.

File "C:\Users\jcubio\AppData\Local\Programs\Python\Python38-32\lib\telnetlib.py", line 317, in read_until
    self.fill_rawq()
  File "C:\Users\jcubio\AppData\Local\Programs\Python\Python38-32\lib\telnetlib.py", line 526, in fill_rawq
    buf = self.sock.recv(50)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

I tried telneting to the switch using putty and cmd and it was successful. I also tried the script in a gns3 environment and it was successful.

 

What would be the issue in this case? Please advise

 

Thank you

 
 

 

 

1 Accepted Solution

Accepted Solutions

balaji.bandi
Hall of Fame
Hall of Fame

Add debug and see what is wrong on the script

 

tn = telnetlib.Telnet(HOST)
tn.set_debuglevel(1000)

 

BB

***** Rate All Helpful Responses *****

How to Ask The Cisco Community for Help

View solution in original post

5 Replies 5

balaji.bandi
Hall of Fame
Hall of Fame

Add debug and see what is wrong on the script

 

tn = telnetlib.Telnet(HOST)
tn.set_debuglevel(1000)

 

BB

***** Rate All Helpful Responses *****

How to Ask The Cisco Community for Help

Hi Sir @balaji.bandi,

Debug shows it's passing the "User Name:" instead of "Username:" but in the script it is 

tn.read_until(b"Username: ")

 

Telnet Debug:

Telnet(192.168.0.2,23): recv b'\r\nUser Name:'

What should I change in the script?

 

Thank you very much

balaji.bandi
Hall of Fame
Hall of Fame

Can you post completely debug output as an attachment to understand better, please?

BB

***** Rate All Helpful Responses *****

How to Ask The Cisco Community for Help

Hi Sir @balaji.bandi,

It works now. The issue is the spacing. Instead of 

tn.read_until(b"Username: "), The telnet prompt is 
tn.read_until(b"Username:").
 
Thanks for the help sir.

balaji.bandi
Hall of Fame
Hall of Fame

No worries, some time it happens blank space, depends on the editor you use - notepad ++ is good.

 

Glad all working as expected. and thank you marked as a solution.

BB

***** Rate All Helpful Responses *****

How to Ask The Cisco Community for Help