1

I do have a list of *.ovpn configuration inside the directory of /etc/openvpn/ovpn_tcp/

inside that directory i do have a bash script called go

include the following code which will pickup random server from the list and connect to it.

#!/bin/bash

set -- *.nordvpn.com.tcp.ovpn
shift $(( RANDOM % $# ))
openvpn "$1"

I tried to create alias to call the script by the following.

alias vpn='bash /etc/openvpn/ovpn_tcp/go'

But it's keep giving me an error

Options error: In [CMD-LINE]:1: Error opening configuration file: *.nordvpn.com.tcp.ovpn
Use --help for more information.

But if i call it by the following alias so it's will run without any issue.

alias vpn='cd /etc/openvpn/ovpn_tcp/ && bash go'

Usually i open screen session to connect to the vpn and then detached it and once I'm done so i reattach to it and then use CTRL + C to cancel the vpn connection.

What I'm looking for is to set 2 aliases

1- alias to turn on the vpn without needing to open screen session or busy the current terminal and once the vpn connected i want to make sure it's connected by calling curl ifconfig.co to view the IP.

2- alias to turn off the vpn.


NOTE:

Are it's possible to prevent the alias which turn on the vpn to run in case if if we are already connected to VPN?

1 Answer 1

1
  • Use full path in set command
  • run screen in detached mode
  • use a case ... esac construct to make a start/stop script.

Maybe something like this:

#!/bin/bash

start(){
  status # Print IP before connection
  set -- /etc/openvpn/ovpn_tcp/*.nordvpn.com.tcp.ovpn
  shift $(( RANDOM % $# ))
  screen -S vpn -dm openvpn "$1" # connect
  sleep 5 # wait for connection
  status # Print IP after connection
}
stop(){
  screen -S vpn -X quit
  pkill -f ovpn
}
status(){
  printf 'IP: %s\n' "$(curl -s ifconfig.co)"
}

case "$1" in
start)
    if screen -ls | grep -w vpn; then
      echo "Vpn already connected";
      status
    else
      start
    fi
    ;;
stop)
    stop
    ;;
*)
    status
    ;;
esac

and then you can add this as an alias:

alias vpn='bash /etc/openvpn/ovpn_tcp/go'

Usage:

# Start connection
vpn start

# Stop connection
vpn stop

# get status
vpn

As an alternative to an alias, you can put the script in your ~/bin, make it executable and add that directory to your $PATH.

3
  • extra-alternatively, cd /etc/openvpn/ovpn_tcp/ before running the set
    – Jeff Schaller
    Commented May 21, 2019 at 14:31
  • I like absolute paths ;-) Makes working with e.g. history so much easier. Would not matter in this case, is just a general habit.
    – pLumo
    Commented May 21, 2019 at 14:33
  • added this to the script. Let's clean the comments =)
    – pLumo
    Commented May 22, 2019 at 7:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .