OpenVPN & Network Manager: selecting a random VPN target each time you start the Virtual Private Network (UNIX/Linux) SOLVED

I sometimes perform some IT work for a nonprofit organization. They use OpenVPN for their network but since they reside in different locations, they have multiple OpenVPN servers set up rather than just one point of entry. The problem I’ve noticed is that at times one or another will be slower. While I don’t have a mechanism to identify which is faster, I can roll the dice and have my vpn start script pick a random server instead of me having to randomly pick one myself.


# If the network card is unavailable, we're not going to bring up the vpn

# VPN_LIST is just a simple array
declare -a VPN_LIST

# BASH arrays start with index 0

# read the vpn list into an array
while read TMP_VPN; do
done < vpns.txt 

# if the vpns.txt is NOT empty
if (( i >= 0 )); then
    # Choose a random VPN index from the TMP_VPN array
    if (( i > 0 )); then
        ((i - 1))
        ((RANDOM_VPN = $RANDOM % $i))

    # We set the VPN_CONNECTION_NAME to the VPN we chose

    DEFAULT_CONNECTION=$( nmcli con show --active |grep "${REQUIRED_CONNECTION_NAME}" )
    VPN_CONNECTION=$( nmcli con show --active | grep "${VPN_CONNECTION_NAME}" )

    # Make sure that the vpn connection isn't already up
    if [[ "${DEFAULT_CONNECTION}" != "${VPN_CONNECTION}" ]]; then
        echo -n "Connecting to ${VPN_CONNECTION_NAME} ... "

        # The credentials are stored in my Gnome keyring so I run the nmcli command as jason
        su - jason -c "nmcli con up id \"${VPN_CONNECTION_NAME}\""


        if (( RC == 0 )); then
            echo "SUCCESS"
            echo "FAILED"
        echo "configuration mismatch"

exit $RC

The file vpns.txt is simply a text file with the names of the VPNs as they are listed in OpenVPN (see /etc/NetworkManager/system-connections for the list of defined VPNs). One VPN per line.
Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.