0

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

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

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
4

2 回答 2

1

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

这在 bash 中效果最好,但是您可以进行子进程,或者您喜欢通过 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 包装器。ParamikoFabric一起使用。

于 2013-07-28T23:30:11.980 回答
1

您可以使用安装jumpssh pypipip

pip install jumpssh
于 2019-07-26T05:57:34.387 回答