Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launch vpn with python script

Tags:

python-3.x

vpn

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

like image 689
Charles Verleyen Avatar asked Feb 12 '18 20:02

Charles Verleyen


People also ask

Can I use OpenVPN as a VPN?

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.


2 Answers

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.

like image 81
salaheddine Rmaili Avatar answered Nov 15 '22 09:11

salaheddine Rmaili


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.

like image 38
AfroThundr Avatar answered Nov 15 '22 10:11

AfroThundr