expect script not working in for loop
5,952
Try this:
#!/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
}
}
Author by
Shanker
Updated on September 18, 2022Comments
-
Shanker almost 2 years
Need to login to multiple host I am unable to decide how can we add hostname variable in this script array or list. could any one suggest.
And the second thing is that i am getting error while executing this script.
#!/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
After adding only one shebang here is the below error.
spawn sh -c cd /backup/ wrong # args: should be "for start test next command" while executing "for ((i=0" (file "./backup.py" line 14)
-
smw over 6 yearsFor a start, I don't think the system knows that it's an expect script - you need a suitable shebang (or to run it explicitly with
expect -f
) -
Shanker over 6 yearsNow i have edited the question with the shebang, do you want me to edit it as
expect -f
. -
smw over 6 yearsAFAIK you can't have two sebangs: your code is still being executed using
bash
(which explains the majority of the error messages - such asspawn: command not found
and so on) -
Shanker over 6 yearsSo i have added only one shebang of expect, now the error is something different, edited the question.
-
smw over 6 yearsThat would be because you are trying to use a
bash
construct inexpect
I think. For theTcl
/expect
equivalent, see for example wiki.tcl.tk/1015
-
-
Angel Todorov over 6 yearsAlso, I don't see where you set the
$file
variable. -
Shanker over 6 yearsActually while executing the command we give an argument that is called here as file.
-
Shanker over 6 yearsset list {host001, host002, host003} is not working. calling it in this way.
spawn sh -c "ssh $list < ./backup.py > /backup/dbbackup-$file-$date.txt"