2016-11-09 41 views
0

我嘗試使用期望腳本向遠程服務器發送命令時遇到問題。 如果我在腳本中手動將其插入send命令中,該命令正常,但如果通過參數($ command)將其傳遞給except腳本,則該命令無效。 我想在遠程服務器上運行的命令是:期望命令變量與管道和特殊字符不起作用

top -b -n 2 |頭-15 & & ls -lrt/var/log |頭-10

例:./myexpectscript密碼IP 「頂-b -n 2 |頭-15 &」

更新:我發現我發的每一個命令(即多單字符串),通過這個腳本在遠程服務器括號內執行... 例如:

./myexpectscript密碼IP「PWD」是確定

./myexpectscript密碼IP「回聲你好」答案是:

# {echo hello} 
/bin/sh: {echo: not found 

如果我刪除了雙引號的命令作品:

./myexpectscript密碼IP回聲你好

# echo hello 
hello 

所以,問題是,我想執行一個多管道單線命令:

top -b -n 2 | head -15 && ls -lrt /var/log | head -10 

在服務器上通過不同的腳本我我:

# {top -b -n 2 | head -15 && ls -lrt /var/log | head -10} 
    /bin/sh: {top: not found 
    ls: /var/log: No such file or directory 
    head: invalid number '10}' 

這應該使用雙引號,但我得到了大括號中的命令。 我在其他類型的服務器上試過這個腳本,並且我得到了相同的行爲。

#!/usr/bin/expect -f 
set password [lrange $argv 0 0] 
set ipaddr [lrange $argv 1 1] 
set command [lrange $argv 2 end] 
set timeout -1 
spawn ssh [email protected]$ipaddr 
match_max 100000 
expect "*?assword:*" 

send -- "$password\r" 

expect "*\\\[0-7\\\]:*" 
send -- "5\r" 

expect "*\\\[0-4\\\]:*" 
send -- "3\r" 

expect "\\\#*" 

#spawn {*}$command 
#eval spawn $command 
#send -- "$command\r" 
send -- "top -b -n 2 | head -15 && ls -lrt /var/tslog | head -10\r" 

expect "\\\#*" 
send -- "exit\r" 

expect "*\\\[0-4\\\]:*" 
send -- "0\r" 

expect "*\\\[0-7\\\]:*" 
send -- "0\r" 


expect eof 
+0

顯示你究竟是如何作爲一個參數提供的命令將期望腳本 –

回答

0

使用lindex而不是lrange

#!/usr/bin/expect -f 
set password [lindex $argv 0] 
set ipaddr [lindex $argv 1] 
set command [lindex $argv 2] 
... ... 
send -- "$command\r" 

並調用你的腳本是這樣的:

./myexpectscript password ip "echo hello world" 
+0

我更新了主要帖子,我希望現在更加註意。謝謝你的回答,我已經試圖在雙引號內通過它,但沒有成功。 – SimoneM

+0

就是這樣!非常感謝你。 – SimoneM