Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Python libs such as Paramiko for chain connections with Telnet and SSH

Similar to a question asked here: SSH and telnet to localhost using python

I'm trying to find a solution to the following problem:

From Server A (full rights) over Jumhost B (no sudo), I want to connect to several Network devices using Python (one after another is enough, it doesn't have to be in the same time). With SSH only this would be no problem but a lot of devices use Telnet only (I know that this isn't secure, but it wasn't my decision to do it like that).

After research I came across multiple solutions for chain SSH connections, such as Paramiko, Netmiko, Pxssh etc. But I can't find a proper way to achieve the last step with Telnet. Currently I have the following code:

class SSHTool():
def __init__(self, host, user, auth,
             via=None, via_user=None, via_auth=None):
    if via:
        t0 = ssh.Transport(via)
        t0.start_client()
        t0.auth_password(via_user, via_auth)
        # setup forwarding from 127.0.0.1:<free_random_port> to |host|
        channel = t0.open_channel('direct-tcpip', host, ('127.0.0.1', 0))
        self.transport = ssh.Transport(channel)
    else:
        self.transport = ssh.Transport(host)
    self.transport.start_client()
    self.transport.auth_password(user, auth)

def run(self, cmd):
    ch = self.transport.open_session()
    ch.set_combine_stderr(True)
    ch.exec_command(cmd)
    retcode = ch.recv_exit_status()
    buf = ''
    while ch.recv_ready():
        buf += str(ch.recv(1024))

    return (buf, retcode)


host = ('192.168.0.136', 22)
via_host = ('192.168.0.213', 22)

ssht = SSHTool(host, '', '',
via=via_host, via_user='', via_auth='')

output=ssht.run('ls')
print(output)

With this I am able to chain through my Jumphost, but I don't know how to implement then a Telnet connection. Does anyone know a proper solution?

like image 690
vato2 Avatar asked Oct 28 '22 23:10

vato2


1 Answers

You cannot use "channel" class with Telnet class. Telnet class needs to connect to a host:port. So you need to start listening on a local temporary port and forward that to "channel" class. There's a ready-made forward_tunnel function in Paramiko forward.py demo exactly for this purpose:

forward_tunnel(local_unique_port, telnet_host, 23, t0)
telnet = Telnet("localhost", local_unique_port)
like image 95
Martin Prikryl Avatar answered Nov 15 '22 07:11

Martin Prikryl