python ssh进入跳转服务器,然后从跳转服务器ssh进入主机以执行命令 [英] python ssh in to a jumpserver and then ssh in to a host from the jumpserver to execute a command

查看:39
本文介绍了python ssh进入跳转服务器,然后从跳转服务器ssh进入主机以执行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 SSH 连接到一个跳转服务器.从跳转服务器,我希望通过 SSH 连接到主机并执行命令:'rpm -qa |grep package' 并获取输出.完成后,我想先成功注销主机,然后再注销跳转服务器.

I want SSH to a jumpserver. From the jumpserver, I want SSH to a host and execute a command: 'rpm -qa | grep package' and get the output. Once done, I want successfully logout of the host first and then logout of the jump server.

以下是我迄今为止尝试过的:

Below is what I have tried thus far:

Import pexpect

options = '-q -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oPubkeyAuthentication=no'

child = pexpect.spawn('ssh ssheth@jumpserver %s'%(options), timeout=None)
child.expect(['password: '])
child.sendline('hello123')
child.expect('#')
child.sendline('ssh ssheth@host "rpm -qa | grep -v watch | grep extractor"')
child.expect(['password: '])
child.sendline(password)
child.logfile = fout
child.expect(".*\$ ", timeout=None)
child.close()

这会引发以下异常:

Timeout exceeded in read_nonblocking().
<pexpect.spawn object at 0x7f007800d190>
version: 2.4 ($Revision: 516 $)
command: /usr/bin/ssh
args: ['/usr/bin/ssh', 'ssheth@jumpserver', '-q', '-oStrictHostKeyChecking=no', '-oUserKnownHostsFile=/dev/null', '-oPubkeyAuthentication=no']
searcher: searcher_re:
    0: re.compile("#")
buffer (last 100 chars): ssheth@jumpserver:~[ssheth@jumpserver ~]$ 
[ssheth@jumpserver ~]$ 
before (last 100 chars): ssheth@jumpserver:~[ssheth@jumpserver ~]$ 
[ssheth@jumpserver ~]$ 
after: <class 'pexpect.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 27286
child_fd: 91
closed: False
timeout: 2
delimiter: <class 'pexpect.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1

推荐答案

最简单的答案是打开一个端口转发到远程服务器.

Simplest answer is to open a port forwarding to the remote server.

这在 bash 中效果最好,但您可以进行子处理,或者您喜欢通过 python 运行它的任何方式.

This works best in bash, but you can subprocess, or whatever you prefer to run it through python.

假设 IP 是:

  • 跳转服务器 IP 为 151.121.121.121
  • 最终服务器 IP 为 10.1.2.3

点赞关注

# Open a local port 13000 that will map through jumpserver and 
# connect to finalserver on port 22
ssh -L 13000:10.1.2.3:22 username@151.121.121.121
# Then open an ssh session to localhost:13000 (which will forward to the
# finalserver.com and run your command)
ssh username@localhost -p 13000 'rpm -qa | grep package'

旁白:查看您的期望脚本并记住过去.Python 有一些 ssh 包装器.Paramiko面料.

Aside: looking at your expect script and remembering the old days. Python has some ssh wrappers. Paramiko is used with Fabric.

这篇关于python ssh进入跳转服务器,然后从跳转服务器ssh进入主机以执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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