简体   繁体   中英

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 user@192.168.0.1
user@192.168.0.1'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?

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..

You could just use

ssh -t -p 2228 user@192.168.0.1 "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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM