Search code examples
pythonnetwork-programmingsshtelnet

python Telnet through a SSH tunnel


I wrote a python script that will start an SSH session, and afterwards it will Telnet into a switch. using pexpect, pxssh and telnetlib.

everything seems to be working and I am able to access some switches. but for the majority I get this error:

socket.error: [Errno 111] Connection refused

OR sometimes:

NO ROUTE TO HOST

I checked, there is a server listening on the default port, and my firewall is turned off.

  • as a note there are no restrictions on the switch, and my IP is whitelisted*

also what seems off, when I try to use SSH and TELNET commands outside the script (in shell), everything will work and I can access the switch.

I would appreciate any feedback.

from pexpect import pxssh
import sys
import telnetlib
s = pxssh.pxssh()
hostname = ('#')
username = ('##')
password = ('###')

#LOGIN TO SSH HOST
s.login(hostname,username,password)

user=('####')
passw=('#####')
tn = telnetlib.Telnet(host)
tn.read_until("username: ")
tn.write(user+"\n")
tn.read_until("password: ")
tn.write(passw+"\n")
tn.write("terminal length 0\n")
tn.write("show interface description\n")
tn.write("exit\n")
data = tn.read_all()
print data

Solution

  • SSH isn't really a tunnel itself; it's an application layer protocol. Telnet, which is also an application layer protocol, needs at least TCP layer tunnel. If you want to telnet inside SSH, you need to use telnet command on the remote server via SSH instead.

    from pexpect import pxssh
    
    s = pxssh.pxssh()
    hostname = ('#')
    username = ('##')
    password = ('###')
    s.login(hostname,username,password)
    
    s.sendline('telnet [your hostname]')
    s.sendline('show interface description\n')