In the previous post I explained step by step how to set up a VPN connection in Raspberry Pi. When you want to connect to the VPN you have to run the following command:
sudo openvpn config-filename-goes-here.ovpn
where config-filename-goes-here.ovpn is the VPN configuration file. The only problem is that every time you want to connect to the VPN you have to manually execute this command. It would be much more convient to run it automatically during the system startup. So let’s do it..
Firstly, you need to create a script in /etc/init.d directory:
sudo nano /etc/init.d/VPNConnection
where VPNConnection is the name of the script (you are free to choose any name that you prefer).
Once the nano editor is open, just copy and paste the following content:
#! /bin/sh
# /etc/init.d/VPNConnection### BEGIN INIT INFO
# Short-Description: Simple script to start a program at boot
# Description: A simple script from http://www.stuffaboutcode.comwhich will start / stop a program a boot / shutdown.
### END INIT INFO# If you want a command to always run, put it here
# Carry out specific functions when asked to by the system
case “$1” in
start)
echo “Starting VPN Connection”
# Connect to the VPN
cd /etc/openvpn
sudo openvpn config-filename-goes-here.ovpn
;;
stop)
echo “Stopping VPN Connection”
# Disconnect
killall openvpn
;;
*)
echo “Usage: /etc/init.d/VPNConnection {start|stop}”
exit 1
;;
esac
Now you can save and close the editor. The next step is to make the script executable:
sudo chmod 755 /etc/init.d/VPNConnection
Before to proceed any further test if the script works as expected. Try to connect to the VPN using the following command:
sudo /etc/init.d/VPNConnection start
and then test the stop command (disconnect from the VPN):
sudo /etc/init.d/VPNConnection stop
The final step is to register the script to be run at boot and shutdown:
sudo update-rc.d VPNConnection defaults
Next time you will boot the system you will be automatically connect to the VPN.
If you want to remove the script from the start-up:
sudo update-rc.d -f VPNConnection remove
Let me know if you have any comments or suggestion!