I need to be able to turn on my vpn in a python script and then terminate it. Very easy to do it manually (see picture in the link below) but I have no idea how to code it. I heard about subprocess.Popen but not sure if I am on the right track.
manual way of turning on my vpn
I am using Ubuntu 16.04 and my VPN is TrustZone.
Thank you for your help.
Charles
Download and install a connection setting file (. ovpn file) of OpenVPN (only once at the first time) You have to download an OpenVPN connection setting file (. ovpn) in order to connect to a VPN Gate Public VPN Relay Server by using OpenVPN.
I've been working on something similar and it work fine with python on Debian and Ubuntu, It depend on openvpn So make sure to install openvpn in your machine using :
Sudo apt-get update
Sudo apt-get install openvpn
Then you can use this small peace of python code (vpn.py) to run the vpn make sure you use the sudo and before run it use the chmod 777 on the file. In your case you're using trustzone make sure to generate the config file with the extension .ovpn
https://trust.zone/setup/ubuntu/ovpn/za
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests, os, sys, subprocess, time
path = '/home/user/Download/trustedzone.ovpn'
with open("/home/user/Download/trustedzone.ovpn", "a") as myfile:
myfile.write('\nscript-security 2\nup /etc/openvpn/update-resolv-conf\ndown /etc/openvpn/update-resolv-conf')
myfile.close()
x = subprocess.Popen(['sudo', 'openvpn', '--auth-nocache', '--config', path])
try:
while True:
time.sleep(600)
# termination with Ctrl+C
except:
try:
x.kill()
except:
pass
while x.poll() != 0:
time.sleep(1)
Place The script where you want to run it then use the command
Sudo chmod 777 vpn.py
To start The vpn client Run
Sudo ./vpn.py
Wish it will work for you, have a good journey.
Taking a wild stab from that screenshot, your VPN appears to be configured using NetworkManager. In that case, the following commands would start and stop your VPN:
import os
os.system('nmcli c up <VPN_NAME>') # Start the VPN
os.system('nmcli c down <VPN_NAME>') # Stop the VPN
You can find more info on running system commands from the interpreter here, and on using NetworkManager commands here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With