Shell-Script

期望腳本在 for 循環中不起作用

  • November 14, 2017

需要登錄到多個主機我無法決定如何在這個腳本數組或列表中添加主機名變數。任何人都可以建議。

第二件事是我在執行這個腳本時遇到了錯誤。

#!/usr/bin/env expect
set timeout 12
set date [exec date "+%d-%B-%Y"]
spawn sh -c "cd /backup/"

for ((i=0;i<8;i++))

do

spawn sh -c "ssh host001n < ./backup.py > /backup/dbbackup-$file-$date.txt"
expect "Enter passphrase for key '/root/.ssh/id_rsa':"
send "pass\r"
expect "Enter passphrase for key '/root/.ssh/id_rsa':"
send "pass\r"
expect "Enter passphrase for key '/root/.ssh/id_rsa':"
send "pass\r"
expect "Password:"
send "pass\r"
interact

done

在此處僅添加一個 shebang 後,出現以下錯誤。

spawn sh -c cd /backup/
wrong # args: should be "for start test next command"
   while executing
"for ((i=0"
   (file "./backup.py" line 14)

試試這個:

#!/usr/bin/env expect
set timeout 12
set date [timestamp -format "+%d-%B-%Y"]    ;# don't need to call out to date
cd /backup                                  ;# use the built-in cd command

# need to use Tcl syntax for the for loop, not shell syntax
for {set i 0} {$i < 8} {incr i} {
   spawn sh -c "ssh host001n < ./backup.py > /backup/dbbackup-$file-$date.txt"

   # more DRY
   expect {
       "Enter passphrase for key '/root/.ssh/id_rsa':" {
           send "pass\r"
           exp_continue
       }
       "Password:" {send "pass\r"}
       eof
   }
}

引用自:https://unix.stackexchange.com/questions/404367