How To... | Why not..? | Scripts | Patches | ![]() |
Last update: 2018-08-11
Author: Bruno Flückiger
In this post I describe how to write a shell script that provides you with a list of available OpenVPN connections to choose from. The script uses only tools available on OpenBSD. You don't need to install any other package than OpenVPN. You can use the mechanism of this script to present a choice for something else than OpenVPN.
First of all, you should install the software you want to use. In my case this is OpenVPN:
$ doas pkg_add -i openvpn
doas (user@fqdn.example.com) password:
After the installation of OpenVPN I create a directory in my $HOME. In this new directory I will store the required configuration files for OpenVPN:
$ cd ~
$ mkdir .openvpn
As the last step of preparation I copy the required files to the new folder. In the case of OpenVPN I have one file with the extension .ovpn per connection.
The selection script looks like this:
#!/bin/ksh
d=~/.openvpn
[[ ! -d $d ]] && exit 0
c=$(find $d -name "*.ovpn" | wc -l)
[[ "$c" -lt 1 ]] && exit 1
if [ "$c" -lt 2 ] ; then
f="$(find $d -name "*.ovpn")"
else
set -A v $(/bin/ls $d/*.ovpn)
a="-buttons "
m=$(mktemp /tmp/vpnXXXXXXXX)
for i in $(jot -ns " " - 0 $((${#v[@]}-1))) ; do
a="$a#$i:$i,"
echo "$i $(basename ${v[$i]} | sed 's/.ovpn//')" >> "$m"
done
j=$((i+1))
xmessage $a"Cancel:$j" -file "$m" -geometry 400x200
r=$?
[[ $r -eq $j ]] && exit 0
f=${v[$r]}
rm -rf "$m"
fi
xterm -geometry 80x25 -e doas openvpn --config "$f"
It will show you the list of file names without extension .ovpn
it finds in the
folder ~/.openvpn
. The script uses xmessage(1)
to display the selection dialog. Each file name has a number in front of it. At
the bottom of the dialog box you find the corresponding buttons. Clicking on one
of the buttons will start openvpn with the selected config file in a new xterm(1).
If the script finds only one config file in the folder it will start openvpn in
xterm(1) using this config file right away. If the folder doesn't exist or
doesn't contain any files with the extension .ovpn the script will simply exit.