我如何使用 Python 库(例如 Paramiko)与 Telnet 和 SSH 进行链式连接

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

类似于此处提出的问题:

我正在尝试找到以下问题的解决方案:

从服务器 A(完全权限)通过 Jumhost B(无 sudo),我想使用 Python 连接到多个网络设备(一个接一个就够了,它不必在同时)。仅使用 SSH 就没有问题,但很多设备仅使用 Telnet(我知道这不安全,但我并没有决定这样做)。

经过研究,我遇到了多种用于链式 SSH 连接的解决方案,例如 Paramiko、Netmiko、Pxssh 等。但是我找不到合适的方法来使用 Telnet 实现最后一步。目前我有以下代码:

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)

有了这个,我可以链接我的 Jumphost,但我不知道如何实现 Telnet 连接。有谁知道合适的解决方案吗?

您不能将 "channel" class 与 Telnet class 一起使用。 Telnet class 需要连接到 host:port。因此,您需要开始监听本地临时端口并将其转发到 "channel" class。 Paramiko forward.py demo 中有一个现成的 forward_tunnel 函数正是为了这个目的:

forward_tunnel(local_unique_port, telnet_host, 23, t0)
telnet = Telnet("localhost", local_unique_port)