Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Expect inside a Bash script

Tags:

bash

expect

This is the code snippet I am using in the following Bash script:

  for user_input in `awk '{print}' testfile_$$.txt`
    do
    ipaddress=`echo $user_input | cut -d';' -f 1`
    command="${config_mode}`echo $user_input | cut -d';' -f 2-`"
            ping -w 1 $ipaddress 1> /dev/null 2> $ERR_LOG_FILE 1> $LOG_FILE
    if [ $? -eq 0 ];then
            ssh "$USERNAME@$ipaddress" "$command"
                                                  >> $LOG_FILE


    fi
    done

How do I use Expect to automate the SSH login in this script?

I am very new to Expect and started testing this (it failed):

#!/usr/bin/bash


set force_conservative 0  ;# Set to 1 to force conservative mode even if
                          ;# script wasn't run conservatively originally
if {$force_conservative} {
        set send_slow {1 .1}
        proc send {ignore arg} {
                sleep .1
                exp_send -s -- $arg
        }
}

#

set timeout -1
spawn ssh [email protected] {uname -a; df -h}
match_max 100000
expect "*?assword: "
send -- "bar01\r"
expect eof

Do I need to write the Bash script all over again in an Expect script or can Expect be used inside a Bash script?

If it can be done:

Moreover, I need to get the Bash variables $command, $username, $password, and $ipaddress and use it in the Expect part.

What solution would you suggest?

Or can I create an Expect script and call it from the Bash script just for login, error handling, execution, and logfiles.

like image 268
munish Avatar asked Feb 28 '13 10:02

munish


1 Answers

Well, you will need to run two separate scripts, a shell script that calls an Expect script:

#!/usr/bin/bash


set force_conservative 0  ;

Change the above to

#!/usr/bin/expect

set force_conservative 0  ;

Or alternatively in your shell script I am unsure about the format, but you can send expect -c with the command to execute:

expect -c "send \"hello\n\"" -c "expect \"#\""
expect -c "send \"hello\n\"; expect \"#\""

Actually, there is also one other alternative:

#!/bin/bash

echo "shell script"

/usr/bin/expect<<EOF

set force_conservative 0  ;# Set to 1 to force conservative mode even if
                          ;# script wasn't run conservatively originally
if {$force_conservative} {
        set send_slow {1 .1}
        proc send {ignore arg} {
                sleep .1
                exp_send -s -- $arg
        }
}

#

set timeout -1
spawn ssh [email protected] {uname -a; df -h}
match_max 100000
expect "*?assword: "
send -- "bar01\r"
expect eof
EOF
like image 50
V H Avatar answered Oct 17 '22 11:10

V H