使用Paramiko从服务器进入路由器

时间:2019-07-25 21:04:32

标签: python 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()

我试图使用paramiko进入服务器,然后进入服务器中的路由器,然后运行命令。

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

有帮助吗?

1 个答案:

答案 0 :(得分:1)

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

Paramiko forward.py demo中有一个现成的forward_tunnel函数正是用于此目的。

另请参阅Port forwarding with Paramiko


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

  1. OpenSSH ssh在提示输入密码时需要终端,因此您需要设置SSHClient.exec_commandget_pty参数(这可能会给您带来很多讨厌的副作用)。

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

  3. 然后您需要将{sub1}命令写入ssh输入。
    参见Execute (sub)commands in secondary shell/command on SSH server in Paramiko

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

但是方法通常容易出错。