TCL Expect kills child of child process

旧街凉风 提交于 2021-01-28 06:06:58

问题


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.


回答1:


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




回答2:


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

expect -timeout -1 -ex "Client killed"

and calling script with &

./vpn.exp &


来源:https://stackoverflow.com/questions/45578588/tcl-expect-kills-child-of-child-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!