我正在尝试使用 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 隧道)通过另一台服务器连接到一台服务器。
参见Nested SSH using Python Paramiko .
<小时/>无论如何,回答你的字面问题:
OpenSSH
ssh
在提示输入密码时需要终端,因此您需要设置SSHClient.exec_command
的get_pty
参数(这会给你带来很多令人讨厌的副作用)。然后您需要将密码写入命令(
ssh
)输入中。然后您需要将(子)命令写入
ssh
输入。
请参阅Execute (sub)commands in secondary shell/command on SSH server in Python Paramiko .
stdin, stdout, stderr = client.exec_command(cmd, get_pty=True)
stdin.write('password\n')
stdin.flush()
stdin.write('subcommand\n')
stdin.flush()
但这种方法一般来说很容易出错。
关于python - 使用 Paramiko 通过另一台服务器连接到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57210100/