3

I could use a little help on this one. I am a novice scripter at best. I am trying to write a bash script to connect to my multiple openvpn sites. I am trying to write the script to open in a detached screen. I have managed to write the script to connect to the different .ovpn via different variables. Getting them to run in the detached screen is what I am having trouble with. Hoping one of you guys might be able to help me. Currently I am just running

screen -S vpn

then once the screen opens up, I execute my script to connect to the openvpn sites. Here is my current vpn connection script:

#!/bin/bash

if [ "$1" = "seed-rl" ] ;
then
cd "/home/robbiel811/vpn configs"
echo password | sudo -S openvpn --config seed-rl.ovpn
fi

if [ "$1" = "atl10" ] ;
then
cd "/home/robbiel811/vpn configs"
echo password | sudo -S openvpn --config Atlanta-10.ovpn
fi

if [ "$1" = "atl11" ] ;
then
cd "/home/robbiel811/vpn configs"
echo password | sudo -S openvpn --config Atlanta-11.ovpn
fi

if [ "$1" = "atl12" ] ;
then
cd "/home/robbiel811/vpn configs"
echo password | sudo -S openvpn --config Atlanta-12.ovpn
fi

if [ "$1" = "nyc02" ] ;
then
cd "/home/robbiel811/vpn configs"
echo password | sudo -S openvpn --config NewYork-02.ovpn
fi

if [ "$1" = "nyc10" ] ;
then
cd "/home/robbiel811/vpn configs"
echo password | sudo -S openvpn --config NewYork-10.ovpn
fi

if [ "$1" = "nyc11" ] ;
then
cd "/home/robbiel811/vpn configs"
echo password | sudo -S openvpn --config NewYork-11.ovpn
fi

What can I do to make this script run in a detached screen?

muru
  • 207,228

1 Answers1

1

You can check if the script is being run inside screen, and if not, re-execute it in screen:

#! /bin/bash

[[ -z $STY ]] && screen -S vpn -d -m "$0" "$@"

if [ "$1" = "seed-rl" ] ;
then
    cd "/home/robbiel811/vpn configs"
    echo password | sudo -S openvpn --config seed-rl.ovpn
fi

...

STY is a variable set by screen, which we can use to detect if we're running in it. $0 is the current command being executed, and $@ all the arguments.

Also, consider simplifying your script using associative arrays:

#! /bin/bash

[[ -z $STY ]] && screen -S vpn -d -m "$0" "$@"


declare -A configs
config['seed-rl']='seed-rl.ovpn'
config['atl10']='Atlanta-10.ovpn'
# ... etc.
config['nyc11']='NewYork-11.ovpn'

cd "/home/robbiel811/vpn configs"
echo password | sudo -S openvpn --config "${config[$1]}.ovpn"

And using NOPASSWD sudoers rules instead of storing your password in clear text.

muru
  • 207,228