I am trying to achieve the following:
./vpnconnect.sh start should establish a VPN connection to a server. ./vpnconnect.sh stop should terminate the VPN connection. Here is the attempted shell script which doesn't work as expected. It gives error:
~$ ./vpnconnect.sh stop
Stopping VPN connection:
./vpnconnect.sh: 22: ./vpnconnect.sh: root: not found
./vpnconnect.sh: 26: ./vpnconnect.sh: 14128: not found
The script:
#!/bin/sh
#
#
#
#
PIDOCN=""
VAR2=""
# Start the VPN
start() {
echo "Starting VPN Connection"
eval $(echo 'TestVpn&!' | sudo openconnect -q -b --no-cert-check 127.0.0.1 -u myUser --passwd-on-stdin)
success $"VPN Connection established"
}
# Stop the VPN
stop() {
echo "Stopping VPN connection:"
VAR2=eval $(sudo ps -aef | grep openconnect)
echo $VAR2
eval $(sudo kill -9 $VAR2)
PIDOCN=eval $(pidof openconnect)
echo $PIDOCN
eval $(sudo kill -9 $PIDOCN)
}
### main logic ###
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status openconnect
;;
restart|reload|condrestart)
stop
start
;;
*)
echo $"Usage: $0 {start|stop|restart|reload|status}"
exit 1
esac
exit 0
The error messages:
./vpnconnect.sh: 22: ./vpnconnect.sh: root: not found
./vpnconnect.sh: 26: ./vpnconnect.sh: 14128: not found
Come from these lines:
VAR2=eval $(sudo ps -aef | grep openconnect)
PIDOCN=eval $(pidof openconnect)
These lines are non-sense. The shell takes the output of the $(...) sub-shells and tries to execute them as commands, with VAR2 and PIDOCN variables set to "eval". This is definitely not what you wanted.
Probably you're looking for something more like this:
stop() {
echo "Stopping VPN connection:"
sudo ps -aef | grep openconnect
sudo kill -9 $(pidof openconnect)
}
The issue is with eval:
VAR2=eval $(sudo ps -aef | grep openconnect)
Here, eval will try to execute the output of sudo ps -aef | grep openconnect command. That's the reason you are getting the errors you are seeing.
Rewrite it as:
VAR2=$(sudo ps -aef | grep openconnect)
Which will simply assign the output of the sudo command pipeline to VAR2 variable. However, you can't use VAR2 as an argument to kill because it contains other tokens like username along with the PID.
In other places where you are doing eval $(command), all you need is command.
You could use pkill openconnect to kill any existing openconnect processes instead of finding out the PID and issuing a kill against it. pgrep and pkill are quite handy for start/stop/restart script like yours.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With