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

烈酒焚心 提交于 2019-12-07 08:00:26

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/53871621/how-do-i-use-python-libs-such-as-paramiko-for-chain-connections-with-telnet-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!