Writing an OpenConnect VPN Connect script in Bash

Table of Contents

img

Bypassing proprietary GUI for VPN connection was a very productive idea, and using OpenConnect to replace the Cisco AnyConnect client which was continually breaking for me proved nice, and provided a nice1 command-line interface to make it scriptable.

This is part of a series2 of articles because making something even as trivial as an API wrapper in Bash, gave me a mortifying glimpse of the antiquity of Bash. So after this article, check out the re-work in Babashka, a fast and much better designed interpreter that works as a shell script.

Bash Wrapper

Most of this is based off openconnect documentation3. Note the bash-typical heavy use of strings, including aliased strings.

#!/bin/bash
on="sudo openconnect VPN.COM --background --authgroup=AUTHGROUP --user=USERNAME"
off="sudo pkill openconnect"
if [[ $1 == "off" ]]; then 
    $off && echo ">>>> VPN off"
elif [[ $1 == "on" ]]; then
    $on && echo ">>>> VPN on"
elif [[ $1 == "reset" ]]; then
    $off;$on && echo ">>>> VPN reset"
elif [[ $1 == "status" ]]; then
    pid=$(pidof openconnect)
    if [[ $pid ]]; then
       echo "VPN On. PID: $pid"
       else
           echo "VPN off."
    fi       
       else
           echo "call with options \"on\", \"reset\", \"status\",  or \"off\""
    fi

Conclusions

This was a tolerably okay little script. What grated on me was the various characteristics of bash: the clumsy if-construct for handling input, the fact that I need to rely on string-passing, and to learn an all-new syntax for functions, etc. Add to this the friction of constanty needing do read docs to decipher when spaces are or are not allowed (and when optional), and likewise for semicolons, and it was no longer fun to write this. Finally, I wanted to extend it with the ability to remain one-line while still providing relatively secure storage of my credentials and this was the deal breaker; one-liners at the CLI have different characteristics than one-liners with aliases which are, in turn, different than one-liners from a script file.

This script is okay if you don’t mind typing in your password; past that, I decided to move to something else.

Footnotes

1 A little weird how it takes credentials, but otherwise nice

2 The whole series can be found here: https://tech.toryanderson.com/tags/openconnect/

3 A copy of the openconnect(8) man page: https://www.systutorials.com/docs/linux/man/8-openconnect/

Tory Anderson avatar
Tory Anderson
Web App Engineer, Digital Humanist, Researcher, Computer Psychologist