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

类似于这里提出的问题:

SSH and telnet to localhost using python

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

从服务器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类一起使用. Telnet类需要连接到host:port.因此,您需要开始侦听本地临时端口并将其转发到“channel”类.在
Paramiko forward.py demo中有一个现成的forward_tunnel函数,用于此目的:

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