1

I have an expect script like this

#!/usr/bin/expect -f
set timeout 30
log_user 0

set PASSWORD $::env(PASSWORD)
set USERNAME $::env(USERNAME)
set TOKEN $::env(TOKEN)

puts stderr "Generating OTP"
spawn oathtool --totp $TOKEN
expect -re \\d+
set otp $expect_out(0,string)

puts stderr "Connecting to VPN server"
spawn -ignore HUP env openconnect -b https://vpn
expect "GROUP:"
send "Tech\n"
expect "Username:"
send "$USERNAME\n"
expect "Password:"
send "$PASSWORD\n"
expect "Password:"
send "$otp\n"
expect EOF

This simple script provides user and password to openconnect to make a new VPN connection in background, but it wont work because the children spawned processes are killed by expect. As you may know, expect will send SIGHUP signal before finish, I was trying to workaround it but even when I put the -ignore HUP flag, it is killing the underlying process, I would like to end my script but the underlying openconnect in background survive.

Do you know what is lacking here?

Take into account that openconnect -b will spawn other PID by its own.

  • This isn't clear enough - can you elaborate: "but it wont work because the children spawned processes are killed by expect, even when I put the -ignore HUP flag, it is killing this underlying process" – Sharad Aug 11 '17 at 16:11
  • I solved this problem using other approach, but I have added more details now, looks better this question? – Jairo Andres Velasco Romero Aug 11 '17 at 16:36

2 Answers2

0

The following method using 2 batch files worked for me:

The -b flag in openconnect is not used and kill command is used instead to send openconnect to background.

contents of file named vpn2:

#!/usr/bin/expect -f
set timeout -1
spawn -ignore HUP -noecho /root/bin/v2vpn2 
expect "password"
sleep 3
send -- "my_password\r"
expect "SMS OTP"
interact 
expect "Established"
expect eof

contents of file named v2vpn2:

rm /var/log/vpn2.log > /dev/null 2>&1

touch /var/log/vpn2.log

# the word password is printed twice and so filtering here

tail -f /var/log/vpn2.log |  grep -m2 -wo "password" | sed '2q;d' &

tail -f /var/log/vpn2.log | grep --color=never -wo "SMS OTP" &

while /bin/true; do

        grep -q "Established" /var/log/vpn2.log 
        if (( $? == 0 )); then
                kill -STOP `pgrep openconnect` 
                kill -CONT `pgrep openconnect` 
                pkill vpn2
                exit
        fi
done & 

openconnect  -u "my_user_name"  my_vpn_url  >> /var/log/vpn2.log 2>&1

the sudhakar
  • 49
  • 3
  • 9
0

After spending too much time on this, I solved it by adding

expect -timeout -1 -ex "Client killed"

and calling script with &

./vpn.exp &