简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM