python ssh进入跳转服务器,然后从跳转服务器ssh到主机执行命令

时间:2013-07-28 22:22:42

标签: python ssh pexpect

我想要一个跳转服务器的SSH。从jumpserver,我想要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

2 个答案:

答案 0 :(得分:1)

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

这在bash中效果最好,但您可以通过python进行子处理或任何您喜欢的操作。

假设IP是:

  • jumpserver IP为151.121.121.121
  • finalserver 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一起使用。

答案 1 :(得分:-1)

您可以使用pip

安装jumpssh pypi
pip install jumpssh