2011-08-12 48 views
-1

我有一個bash + expect腳本,它必須通過ssh連接到遠程comp(並且我不能使用ssh密鑰,在這裏需要密碼標識),讀取在那裏的文件,找到具有「主機名」(如「主機名稱aaaa1111」)的特定行,並將此主機名存儲到while後使用的變量中。我怎樣才能得到「主機名」參數的值?我認爲行內容將在$ expect_out(buffer)變量中(所以我可以掃描它並分析),但事實並非如此。我的腳本是:在遠程計算機上運行cat並使用expect發送輸出變量

#!/bin/bash   
    ----bash part---- 
    /usr/bin/expect << ENDOFEXPECT 
    spawn bash -c "ssh [email protected]$IP" 
    expect "password:" 
    send "xxxx\r" 
    expect ":~#" 
    send "cat /etc/rc.d/rc.local |grep hostname \r" 
    expect ":~#" 
    set line $expect_out(buffer) 
    puts "line = $line, expect_out(buffer) = $expect_out(buffer)" 
    ...more script... 
    ENDOFEXPECT 

當我試試,看看行變量,我只看到這一點:line = , expect_out(buffer) = (buffer)什麼是讓從文件到變量行的路嗎? 或者是否有可能在遠程計算機上打開文件與期望,掃描文件,並得到我需要的變量? 這裏http://en.wikipedia.org/wiki/Expect有一個例子:

# Send the prebuilt command, and then wait for another shell prompt. 
    send "$my_command\r" 
    expect "%" 
    # Capture the results of the command into a variable. This can be displayed, 
    set results $expect_out(buffer) 

似乎並不在這種情況下工作嗎?

+0

請修復您的標題以描述您的問題。 – Brandon

+2

還有問題[出現在serverfault上](http://serverfault.com/q/300238/30957) –

+0

...沒有答案,但不幸的是,不幸的是, – lugger1

回答

1

您可能只想嘗試一切從預期中完成,因爲期望可以控制bash。

以下內容應該做你所描述的。不知道這是否正是你想要做的。

#!/bin/sh 
# the next line restarts using tclsh \ 
exec expect "$0" "[email protected]" 


spawn bash 
send "ssh [email protected]$IP\r" 
expect "password:" 
send "xxxx\r" 
expect ":~#" 
send "cat /etc/rc.d/rc.local |grep hostname \n" 
expect ":~#" 
set extractedOutput $expect_out(buffer) 
set list [split $extractedOutput "\n"] 
foreach line $list { 
    set re {(?x) 
     .* 
     (*)    
     -S.* 
    } 
    regexp $re $line total extractedValue 
    if {[info exists extractedValue] && [string length $extractedValue] > 1} { 
     set exportValue $extractedValue 
     break # We've got a match! 
} 

send "exit\r" # disconnect from the ssh session 

if {[info exists exportValue] && [string length $exportValue] > 1}{ 
    send "export VARIABLE $exportValue\r" 
} else { 
    send_user "No exportValue was found - exiting\n" 
    send "exit\r" 
    close 
    exit 1 
} 

# now you can do more things in bash if you like 
相關問題