2012-05-10 38 views
3

有沒有辦法重定向stdin發送期望,這樣它會被饋送到期望的產卵電話?在我下面的例子中,我將希望嵌入到一個shell函數中,我希望通過heredoc管道傳遞另一個shell腳本,並通過將其捕獲到一個shell變量中來壓縮輸出。重定向期望stdin產卵撥號

psshstdin() { 
     local user=$1 pass=$2 hosts=$3 
     out=$(expect -c ' 
     set timeout 15 
     spawn pssh -i -h '"$hosts"' -p 100 -l '"$user"' -A -o ./ -x-oStrictHostKeyChecking=no <EXPECT_STDIN_HERE 
     expect "assword:" { send '\""$pass\r\""' } 
     interact 
    '<<EOF 
    echo "hello" 
    echo "world" 
    EOF 
    ) 
    } 

SOLUTION:我,因爲我沒有足夠的信譽分,這麼快回答我的問題在這裏張貼此。

我能夠通過嘗試應用this issue中應用的相同技術來解決此問題。我不認爲這個解決方案最初是適用的,但它是。工作代碼如下所示。

psshstdin() { 
    local user=$1 pass=$2 hosts=$3 
out=$(expect -c ' 
set timeout 30 
spawn pssh -I -h '"$hosts"' -p 100 -l '"$user"' -A -o ./ -x-oStrictHostKeyChecking=no 
while {[gets stdin line] != -1} { 
    send "$line\n" 
} 
send \004 
expect "assword:" { send '\""$pass\r\""' } 
expect { 
    "END_TOKEN_OF_SCRIPT" { 
    exit 0 
    } 
    default { 
    exit 1 
    } 
}'<&0) 
} 

我喜歡的東西把它叫做:

psshstdin myusername mypassword ssh_hosts_file<<EOF 
echo "hello" 
echo "world" 
EOF 
+2

該解決方案被發現[這裏](http://stackoverflow.com/questions/10237872/expect-redirect-stdin)。 – user1387661

回答

0

可以捕獲標準輸入到一個變量stdin=$(cat -)

更新:讓我們期待收取標準輸入:

未經測試,但或許:

psshstdin() { 
    local user=$1 pass=$2 hosts=$3 
    out=$(expect -c ' 
    set stdin [read stdin] 
    puts "debug: sending the following stdin to pssh:\n$stdin\n--END--" 
    set timeout 15 
    spawn echo "$stdin" | pssh -i -h '"$hosts"' -p 100 -l '"$user"' -A -o ./ -x-oStrictHostKeyChecking=no 
    expect "assword:" { send "'"$pass"'\r" } 
    interact 
    '<<EOF 
echo "hello" 
echo "world" 
EOF 
) 
} 
+1

這在殼內工作,但似乎沒有記錄的方式將其管入spawn調用的命令。 我在原始代碼的上下文中嘗試了以下內容: 'spawn echo'「$ stdin」'| pssh .....' 'spawn pssh ...'''$ stdin'''' 並且實際上都不能在期望的範圍內正確地管理文本。 – user1387661

+0

你會希望引用它:'spawn pssh ... <{'「$ stdin」'}'。我會在我的答案中提供一個替代方案。 –

+0

我意識到答案是一直存在於現有的stackoverflow問題中。感謝您的快速幫助。 – user1387661