Autoreconnect to VPN service using Monit on Linux is the streamlined method for keeping you automatically connected to your VPN. VPNs nowadays are an essential part of your internet life. Like anything in the tech world they can have hiccups due to the routing involved. This method will use Monit to ping Google every few minutes and if it fails, it will stop OpenVPN and re-establish a fresh connection to your VPN provider like Private Internet Access or Pure VPN. I will assume you have already installed Monit using this guide. This VPN autoreconnect tutorial is thanks to @manne on the forum who wanted an automated solution for reconnecting to his VPN.
|Private Internet Access|
($3.33 / month)
($4.91 / month)
($6.41 / month)
Autoreconnect to VPN Service using Monit + Linux
Preparing for the automation you will need to know where your ovpn file that you use to connect to your VPN is located, I put them in the
Prepare the VPN automation script, you will need a login file containing your credentials
sudo nano /etc/openvpn/login.txt
Enter your credentials for the VPN on separate lines like this
So if the credentials were
I<3MediaServers login.txt would look like this
Ctrl+X, Y and Enter to save
Create the VPN script to reconnect to your VPN service like Private Internet Access
Paste the code below and change
htpcguides to your user
/etc/openvpn/Sweden.ovpn to the OpenVPN configuration file from your provider
#!/bin/bash service openvpn stop echo "$(date +"%F %T") openvpn stopped" >> /home/htpcguides/vpnfixlog.txt service networking stop echo "$(date +"%F %T") network stopped, starting network" >> /home/htpcguides/vpnfixlog.txt service networking start echo "$(date +"%F %T") network started, starting openvpn" >> /home/htpcguides/vpnfixlog.txt service openvpn start echo "$(date +"%F %T") openvpn started, connect to vpn" >> /home/htpcguides/vpnfixlog.txt cd /etc/openvpn sudo openvpn --config /etc/openvpn/Sweden.ovpn --auth-user-pass /etc/openvpn/login.txt echo "$(date +"%F %T") script completed" >> /home/htpcguides/vpnfixlog.txt
Make the script have the right permissions so monit doesn't complain
sudo chmod +x /home/htpcguides/vpnfix.sh
Create the Monit configuration for monitoring the VPN connection
sudo nano /etc/monit/conf.d/vpnmonitor
We are going to monitor the openvpn service and execute a script (we create later) if a ping fails
check process OpenVPN matching "openvpn" start program = "/usr/sbin/service openvpn start" stop program = "/usr/sbin/service openvpn stop" check host ovpn with address 184.108.40.206 if failed icmp type echo count 6 with timeout 30 seconds then exec '/home/htpcguides/vpnfix.sh'
Ctrl+X, Y and Enter to save
Test the monit configuration
sudo monit -t
If all is well then reload Monit
sudo service monit reload
Now when your VPN loses connection for any reason Monit will execute the vpnfix.sh script and re-establish your VPN connection automatically.
You can check the log file to see when the script has executed.