使用 Paramiko 通过另一台服务器连接到服务器 [英] Connecting to a server via another server using Paramiko

查看:55
本文介绍了使用 Paramiko 通过另一台服务器连接到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get into a server using Paramiko and then get into a router that's in the server and then run a command.

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

However, I am not getting a password input for the router and then it just closes the connection.

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 隧道)通过另一台服务器连接到服务器.

First, you better use port forwarding (aka SSH tunnel) to connect to a server via another server.

请参阅使用 Python Paramiko 的嵌套 SSH.

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

Anyway to answer your literal question:

  1. OpenSSH ssh 在提示输入密码时需要终端,因此您需要设置 SSHClient.exec_command(这可以让你得到很多讨厌的副作用).

  1. OpenSSH ssh needs terminal when prompting for a password, so you would need to set get_pty parameter of SSHClient.exec_command (that can get you lot of nasty side effects).

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

Then you need to write the password to the command (ssh) input.

然后您需要将(子)命令写入 ssh 输入.
请参阅在 Python Paramiko 中的 SSH 服务器上的辅助 shell/命令中执行(子)命令.

And then you need to write the (sub)commands to the ssh input.
See 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()

但这种方法通常容易出错.

这篇关于使用 Paramiko 通过另一台服务器连接到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆