Bash – expect script works fine standalone not from bash script

bashexpect

I am running a expect script,which login to a server check if iptables running and return the log file of the status. There is a hostfile also given with server list and password, expect is being called from a shell script which it sending correct parameter; running those parameters individually i can execute the expect script too, but it is just not working in tandem.
the hostfile below:

cat hostfile
10.20.52.167|abcdef
10.20.52.138|zyxwvu

the shell script being executed:

cat iptables
#! /bin/bash
#!/usr/bin/expect -f
while read line
do
ipaddress=`echo $line | awk -F'|' '{print $1}'`
password=`echo $line | awk -F'|' '{print $2}'`
echo "./testcase_3 $ipaddress \"$password\" "
sleep 5
done < hostfile

And lastly the expect script:

cat testcase_3
#!/usr/bin/expect -f
#! /bin/bash

set timeout 60
set host [lindex $argv 0]
set password [lindex $argv 1]
log_user 1
set user subhasish
set logfile output.txt
foreach host $host password $password {
spawn ssh $user@$host
expect "*?assword:*"
send -- "$password\r"
sleep 2
expect "$"
send -- "sudo su\r"
expect -gl {*password for subhasish:*}
send -- "$password\r"
expect "#"
send -- "service iptables status\r"
log_file /home/subhasish/output.log
expect "#"
log_file
}
send -- "exit\r";
send -- "exit\r";
exit 0

I have got no clue where it is going wrong, please help. The iptables script sends argument like "./testcase_3 ... "******" ", which if i run in the commandline works expected by creating output.log. Nothing happens however if i run the iptables script directly…

Best Answer

Hard to tell because as you're posted, iptables does not invoke the expect script. To debug the expect script, add this near the top: exp_internal 1

Since the shell's read command can grab multiple words if the right field separator is provided, I would write the bash script like this:

while IFS='|' read ipaddress password; do
    echo "./testcase_3 $ipaddress \"$password\""
    ./testcase_3 "$ipaddress" "$password"
    sleep 5
done < hostfile