2012-04-18 118 views
4

我在編程上通過ssh運行本地腳本時遇到了問題。
我不確定這是否是本地主機上的shell變量替換問題。pexpect - 通過ssh運行script.sh

手動運行時,

ssh [email protected] 'bash -s' < /u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin/cpu.sh 

我得到預期的輸出,

CPU pctUser pctNice pctSystem pctIowait pctIdle
全部11.21 0.00 1.50 0.31 86.98
0 0.00 0.00 0.00 0.00 100.00
1 3.00 0.00 1.00 0.00 96.00 ....

,但我得到

bash下運行下面的代碼時沒有這樣的文件或目錄

:/u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin/cpu.sh ,

splunk_bin_dir = '/u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin' 
hostname = 'server1' 
username = 'monit' 
password = 'monit#_' 


command = "/usr/bin/ssh %(username)[email protected]%(hostname)s 'bash -s' < %(splunk_bin_dir)s/cpu.sh" % locals() 
print command 

ssh_new_conn = 'Are you sure you want to continue connecting' 

p = pexpect.spawn(command, timeout=360) 
# Handles the 3 possible connection outcomes: 
# a) Ssh to the remote host for the first time, triggering 'Are you sure you want to continue connecting' 
# b) ask you for password 
# c) No password is needed at all, because you already have the key. 
i = p.expect([ssh_new_conn,'[pP]assword:',pexpect.EOF]) 
print ' Initial pexpect command output: ', i 
if i == 0: 
    # send 'yes' 
    p.sendline('yes') 
    i = p.expect(['[pP]assword:',pexpect.EOF]) 
    print 'sent yes. pexpect command output', i 
    if i == 0: 
     # send the password 
     p.sendline(password) 
     p.expect(pexpect.EOF) 
elif i == 1: 
    # send the password 
    p.sendline(password) 
    p.expect(pexpect.EOF) 
elif i == 2: 
    print "pexpect faced key or connection timeout" 
    pass 

print p.before 

這些印刷輸出,

的/ usr/bin中/ SSH monit的@ server1的 'bash的-s' < /u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin/cpu.sh
初始Pexpect的命令輸出:1
bash中:/ U02/Splunk的/ Splunk的在/ etc /應用/ Splunk_TA_nix /斌/ cpu.sh:沒有這樣的文件或目錄

Pexpect的顛簸到[PP] assword線,所以我猜密碼正確傳遞,

回答

3

這裏從Pexpect的手動注:

請記住,Pexpect不會解釋shell元字符,例如 重定向,管道或通配符(>,|或*)。這是一個常見的錯誤。 如果你想運行一個命令,並通過另一個命令管道,然後 你還必須啓動一個shell。

這是工作線

command = """/bin/bash -c "/usr/bin/ssh %(username)[email protected]%(hostname)s 'bash -s' < %(splunk_bin_dir)s/cpu.sh" """ % locals() 
+0

太感謝你了! 真的不知道這個Pexpect'功能' – 2012-04-18 11:12:02