Launch vpn with python script

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.

Tags:

Python 3.X

Vpn