Bash – Calling an expect script in a loop of a bash scrip

bashexpect

I am trying to loop a list of sites through an expect script. The loop will take my list and read it line by line, change directories to the folder of the site name, then pass the site name to an expect script.

Bash Script:

#!/bin/bash
sites="/home/user/sites.cfg"

while read site; do
  cd /home/user/$site
  pwd
  echo $site
  ./base.sh
done < $sites

Expect Script:

#!/usr/bin/expect

set site [lindex $argv 0]
set timeout 3

logfile services
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no -oUserKnownHostsFile=/dev/null user@$site
expect "password" { send mypassword\r }
expect "#"
send environment\ no\ more\n
expect "#"
send show\ service\ service-using\n
expect "#"
send logout\n

Result:

user@myserver:~$ sh show-database.sh
/home/user/site-01
site-01
show-database.sh: 11: show-database.sh: ./base.sh: not found
/home/user/site-02
site-02
show-database.sh: 11: show-database.sh: ./base.sh: not found

I'm hoping to see a file called services in each folder of each site. I can run the following and it works from CLI, however it doesn't switch directories. This is just the beginning the of a much larger script, which will have a few more things to do in the loop. For now, this is what I have for testing.

./base.sh site-01

Thanks!

Best Answer

You don't need the bash wrapper script for this at all, expect can handle all that:

#!/usr/bin/expect
set timeout 3

set rootdir /home/user
set sites [file join $rootdir sites.cfg]
set fh [open $sites r]

while {[gets $fh site] != -1} {
    set dir [file join $rootdir $site]
    if { ! [file isdirectory $dir]} {
        puts "*** error: $dir does not exist"
        continue
    } 

    cd $dir
    puts [pwd]
    puts $site

    log_file services

    spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no -oUserKnownHostsFile=/dev/null user@$site
    expect "password" 
    send "mypassword\r 
    expect "#"
    send "environment no more\r"
    expect "#"
    send "show service service-using\r"
    expect "#"
    send "logout\r"
    expect eof

    log_file
}
Related Question