OpenConnect autoconnect/reconnect script?

8.1k Views Asked by At

I have this script:

#!bin/bash
NAME="user"
PIDFILE="openconnect.pid"
CERT="user.crt"
KEY="user.key"
PASS="pass"
HOST="https://example.com"
SCRIPT="/etc/vpnc/vpnc-script"

openconnect -b --script $SCRIPT --pid-file=$PIDFILE -c $CERT -k $KEY --key-password=$PASS --user=$NAME $HOST

It works, but sometimes if something goes wrong (restart of server, or some other issues), it disconnects from VPN. And I need to rerun script again. Is there some way I could modify it or add it in cron job or some other way?

Note. When I run this script I need to enter certificate password. So considering security, I'm wondering where I should keep that password for autoreconnect purposes?

2

There are 2 best solutions below

0
On

You can detect if openconnect is still running by checking its PID:

pidof openconnect

This return an exit value of 0 if openconnect still runs otherwise non zero.

You would have a script that looks like that [not tested but should give you a hint]:

#!/bin/bash

OPENCONNECT_PID=""
function checkOpenconnect(){
    ps -p "${OPENCONNECT_PID}"
    # print the status so we can check in the main loop
    echo $?
}

function startOpenConnect(){
    # start here open connect with your params and grab its pid
    openconnect [your params] & OPENCONNECT_PID=$!
}

startOpenConnect

while true
do
    # sleep a bit of time
    sleep 30
    OPENCONNECT_STATUS=$(checkOpenconnect)
    [ $OPENCONNECT_STATUS -ne 0 ] && startOpenConnect
done
0
On
#!/bin/bash

USER="?"
PASSWORD="?"
SERVER="?"
CERT="pin-sha256:?"
CHECK_TIMEOUT=30


run () {
  # Start openconnect
  echo $PASSWORD | openconnect $SERVER --servercert=$CERT --user=$USER --passwd-on-stdin
}

startOpenConnect


until (run); do
  echo "openconnect exited. Restarting process in $CHECK_TIMEOUT seconds…" >&2
  sleep $CHECK_TIMEOUT
done