Unpossible
Unpossible

Reputation: 623

I cant get my expect script to run remote bash script as "expected"

I am trying to run an expect script, which should run a bash script on a remote linux server. The bash script is meant to restart a strongswan IPSec tunnel based on the argument sent via the expect script. Here's my expect script:

#log_user 0

set prompt {\$ >}
expect -re $prompt

set ip 192.168.0.1
set user user
set password 4p4ssw0rd
set target [lindex argv 0]

spawn ssh -p 2228 "$user\@$ip"
expect "password:"
send "$password\r";
expect ">"

send "su -\r"
expect "Password:"
send "$password\r"
expect "#"

send "sh /usr/local/bin/ipsec_fixer.sh $target; exit\r"
expect "#"

Here's the remote script:

target=$1

if [[ -n "$target" ]]; then
        value=`grep -i $target /etc/ipsec.conf -A1  |awk '{print $2}'| tail -n 2 | sed 's/0$//'`
        declare -a args
        args=(  $(grep "$value"* /etc/ipsec.conf | awk '{print $2}') )
        for each in ${args[@]}; do ipsec down $each; sleep 3;  ipsec up $each ; done
else   
        exit 2
fi

The expect script runs, but I get the following output:

 /usr/local/bin/fix_ipsec avpnconnection
spawn ssh -p 2228 [email protected]
[email protected]'s password: 
Last login: Sun Dec 11 05:40:55 2016 from 192.168.0.232
sh /usr/local/bin/ipsec_fixer.sh argv; exit
021 no connection named "-c"
021 no connection named "-c"
021 no connection named "-c"
021 no connection named "-c"
logout
user@remote:/home/login >

I have no idea what is going on. Please what am I doing wrong?

Upvotes: 0

Views: 92

Answers (2)

Unpossible
Unpossible

Reputation: 623

I think I've figured it out: the odd looking

021 no connection named "-c"
021 no connection named "-c"
021 no connection named "-c"
021 no connection named "-c"

lines are from the remote system's shell.

My expect script now looks like this:

set script /usr/local/bin/ipsecfixer.sh

spawn ssh -p 2228 $user@$ip

expect "password:"
send "$password\r";
expect ">"

send "su -\r"
expect "Password:"
send "$password\r"
expect "#"
send "/bin/bash $script $argv\r"
expect "#"

And it does the job, so far..

Upvotes: 1

Eric Duminil
Eric Duminil

Reputation: 54223

You could just use

ssh -t -p 2228 [email protected] "sudo /bin/sh /usr/local/bin/ipsec_fixer.sh $target"

and use SSH Key-Based Authentication.

As for the messages you get, is it possible that the script you're launching has an influence on the current SSH connections?

Upvotes: 0

Related Questions