4

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!

  • You have just cd-ed to a "site" directory, and you want the "./base.sh" script to exist there. Does it? – glenn jackman Oct 5 '15 at 20:34
  • Assuming "base.sh" is the expect script: 1) you don't pass the $site argument to it, and 2) *.sh" is the wrong extension for an expect script – glenn jackman Oct 5 '15 at 20:36
  • I've tested this many ways but must have missed the passing of the $site. This is now working by replacing the ./base.sh with the following line, expect /home/user/./base.sh $site – Pi4All Oct 5 '15 at 21:16
  • Also corrected the logfile with log_file. Thanks @glennjackman – Pi4All Oct 5 '15 at 21:19
  • rename base.sh to base.exp. – glenn jackman Oct 5 '15 at 21:20
5

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.