import-ovpn.sh 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #!/usr/bin/env bash
  2. set -o errexit
  3. set -o pipefail
  4. # Enter your VPN login details here so you won't be asked.
  5. VPN_USER=""
  6. VPN_PASS=""
  7. # Check if file is provided
  8. if [ -z "$1" ]; then
  9. echo "Usage: $0 /path/to/yourfile.ovpn"
  10. exit 1
  11. fi
  12. OVPN_FILE=$1
  13. # Check if the file exists
  14. if [ ! -f "$OVPN_FILE" ]; then
  15. echo "File not found!"
  16. exit 1
  17. fi
  18. # Extract the base name of the file without extension
  19. CONN_NAME=$(basename "$OVPN_FILE" .ovpn)
  20. # Check if the connection already exists
  21. if nmcli connection show | grep -q "$CONN_NAME"; then
  22. echo "Connection $CONN_NAME already exists. Delete it?"
  23. echo "y -> yes | n -> no | c -> connect"
  24. read -p "[y/n/c] > " yn
  25. case $yn in
  26. y) echo "Connection $CONN_NAME is deleted."
  27. nmcli connection delete $CONN_NAME
  28. exit 0
  29. ;;
  30. n) exit 0
  31. ;;
  32. c) if nmcli connection show --active | grep -q "$CONN_NAME"; then
  33. echo "Connection $CONN_NAME is already active."
  34. exit 0
  35. else
  36. nmcli connection up "$CONN_NAME"
  37. echo "VPN connection $CONN_NAME has been successfully connected."
  38. fi
  39. ;;
  40. esac
  41. else
  42. # Import the .ovpn file
  43. nmcli connection import type openvpn file "$OVPN_FILE"
  44. # Set username and password
  45. if [ -z "$VPN_USER" ]; then
  46. read -p "Enter VPN username: " VPN_USER
  47. fi
  48. if [ -z "$VPN_PASS" ]; then
  49. read -sp "Enter VPN password: " VPN_PASS
  50. fi
  51. # Make the connection available for all users
  52. nmcli connection modify "$CONN_NAME" connection.permissions ''
  53. # Modify the connection with the username
  54. sudo nmcli connection modify "$CONN_NAME" +vpn.data username="$VPN_USER"
  55. # Create a secrets file for the password
  56. SECRETS_FILE="/etc/NetworkManager/system-connections/$CONN_NAME.nmconnection"
  57. sudo sed -i "s;\[ipv4\];\[vpn-secrets\]\npassword=$VPN_PASS\n\n\[ipv4\];g" $SECRETS_FILE
  58. sudo sed -i "s;password-flags=1;password-flags=0;g" $SECRETS_FILE
  59. # Ensure that sed modified $SECRETS_FILE
  60. if ! sudo grep -oq "$VPN_PASS" "$SECRETS_FILE"; then
  61. if ! sudo grep -oq "password-flags=0" "$SECRETS_FILE"; then
  62. exit 1
  63. fi
  64. fi
  65. # Ensure the file has the correct permissions
  66. sudo chmod 600 "$SECRETS_FILE"
  67. # Restart NetworkManager to apply changes
  68. sudo systemctl restart NetworkManager
  69. # Connect to the VPN
  70. nmcli connection up "$CONN_NAME"
  71. echo "VPN connection $CONN_NAME has been successfully configured and connected."
  72. fi