Skip to content

Instantly share code, notes, and snippets.

@bsless
Last active September 25, 2024 18:41
Show Gist options
  • Save bsless/90667a5dd8e3bc5218bef2dc12fe7905 to your computer and use it in GitHub Desktop.
Save bsless/90667a5dd8e3bc5218bef2dc12fe7905 to your computer and use it in GitHub Desktop.
Set up a bunch of OpenVPN connections using nmcli with username and password
#!/usr/bin/env bash
USERNAME="$1"
PASS="$2"
for f in *.ovpn
do
name=`basename -s .ovpn $f`;
nmcli connection import type openvpn file $f
nmcli connection modify "${name}" +vpn.data connection-type=password-tls
nmcli connection modify "${name}" +vpn.data username="${USERNAME}"
nmcli connection modify "${name}" +vpn.secrets password="${PASS}"
done
@speckly
Copy link

speckly commented May 15, 2023

This script saved me. Had 50 vpn connections. Like any programmer, they want to automate everything. I wanted to make a script but im very bad at Bash. Then I found this. Can sleep tonight

@tukusejssirs
Copy link

This script could be simplified and improved a bit. One could also add a thrird argument to provide a path where the processed OVPN files should be located. I usually also append the following configuration to nmcli c mod:

  • ipv6.method disabled (I have no IPv6 in my local and remote networks);
  • ipv4.never-default yes (I usually want to connect to specific servers only via the VPN; some VPN servers require it to be set to no though).
#!/usr/bin/env bash

USERNAME="$1"
PASS="$2"

for f in  *.ovpn; do
  nmcli c i type openvpn file "$f"
  nmcli c mod "$(basename -s .ovpn "$f")" \
    +vpn.data "connection-type=password-tls, username=$USERNAME" \
    vpn.secrets "password=$PASS"
done

Changes:

  • I removed unnecessary ; at a command;
  • I replaced deprecated backticks with $();
  • I removed curly brackets from ${name}, ${USERNAME} and ${PASS}, as the curly brackets are unnecessary;
  • I added quotes around f variable in order to make that filenames that contain spaces and special characters don’t cause any issues;
  • I have merged nmcli connection modify commands;
  • I have removed name variable, as it would be used only once;
  • I have removed + before vpn.secrets, as AFAIk there is only one secret (password);
  • I have shortened nmcli connection import to nmcli c i;
  • I have shortened nmcli connection modify to nmcli c mod;
  • I have moved do to the previous line (this change is not necessary, it is only a style preference).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment