使用 Paramiko 通过另一台服务器连接到服务器

Connecting to a server via another server using Paramiko

我正在尝试使用 Paramiko 进入服务器,然后进入服务器中的路由器,然后 运行 命令。

但是,我没有收到路由器的密码输入,然后它就关闭了连接。

username, password, port = ...
router = ...
hostname = ...
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy)
client.connect(hostname, port = port, username = username, password = password)

cmd = # ssh hostname@router

# password input comes out here but gets disconnected

stdin, stdout, stderr = client.exec_command(cmd) 

HERE # command to run in the router
stdout.read()

client.close()

有什么帮助吗?

首先,您最好使用端口转发(也称为 SSH 隧道)通过另一台服务器连接到一台服务器。


无论如何回答你的字面问题:

  1. OpenSSH ssh 在提示输入密码时需要终端,所以你需要设置 SSHClient.exec_commandget_pty 参数(这会让你很讨厌副作用)。

  2. 然后需要将密码写入命令(ssh)输入

  3. 然后您需要将(子)命令写入 ssh 输入。
    参见

stdin, stdout, stderr = client.exec_command(cmd, get_pty=True) 
stdin.write('password\n')
stdin.flush()
stdin.write('subcommand\n')
stdin.flush()

但这种方法一般容易出错。