如何使用 Paramiko 等 Python 库通过 Telnet 和 SSH 进行链式连接

2023-11-29

类似于这里提出的问题:使用 python SSH 和 telnet 到本地主机

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

从服务器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”类与Telnet class. Telnet类需要连接到主机:端口。因此,您需要开始侦听本地临时端口并将其转发到“通道”类。有现成的forward_tunnel函数于帕拉米科forward.py demo正是为了这个目的:

forward_tunnel(local_unique_port, telnet_host, 23, t0)
telnet = Telnet("localhost", local_unique_port)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Paramiko 等 Python 库通过 Telnet 和 SSH 进行链式连接 的相关文章

随机推荐