2013-07-28 73 views
0

我想SSH到跳轉服務器。從jumpserver中,我需要SSH到主機並執行命令:'rpm -qa | grep包「並獲取輸出。完成後,我希望首先成功註銷主機,然後註銷跳轉服務器。python ssh到跳轉服務器,然後從跳轉服務器ssh到主機執行命令

下面是我迄今爲止嘗試:

Import pexpect 

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

child = pexpect.spawn('ssh [email protected] %s'%(options), timeout=None) 
child.expect(['password: ']) 
child.sendline('hello123') 
child.expect('#') 
child.sendline('ssh [email protected] "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', '[email protected]', '-q', '-oStrictHostKeyChecking=no', '-oUserKnownHostsFile=/dev/null', '-oPubkeyAuthentication=no'] 
searcher: searcher_re: 
    0: re.compile("#") 
buffer (last 100 chars): [email protected]:~[[email protected] ~]$ 
[[email protected] ~]$ 
before (last 100 chars): [email protected]:~[[email protected] ~]$ 
[[email protected] ~]$ 
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 

回答

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 [email protected] 
# Then open an ssh session to localhost:13000 (which will forward to the 
# finalserver.com and run your command) 
ssh [email protected] -p 13000 'rpm -qa | grep package' 

旁白:看你的期待腳本並記住過去的日子。 Python有一些ssh包裝器。 ParamikoFabric一起使用。

+0

不幸的是,當我使用本地端口轉發時,無法解析終端服務器的主機名/ IP,因爲它只能通過跳轉服務器訪問。 –

+0

@ssheth,對不起,最後一條SSH線路是錯誤的:(修正了,現在它應該是有意義的) – Jonathan

+0

嗨,喬納森,我很感謝你的回答 - 謝謝你的回覆。您的回覆: 第1步: 的ssh -L 13000:172.31.15.22:22 ssheth @ jumpserver 第2步: $ SSH ssheth @本地-p 13000 我想過另一種方法是使基於公鑰認證從跳轉服務器的最終主機,只需運行以下命令: ssh ssheth @ jumpserver「ssh ssheth @最終主機'rpm -qa | grep -v watch | grep提取器;退出'」 –

相關問題