How to Run Proton VPN in Windows with Python

Deepanshu Bhalla Add Comment

In this tutorial, we will show you how to run Proton VPN in Windows using Python Code.

Prerequisite

First you need to download and install the OpenVPN GUI. OpenVPN GUI is a user-friendly application that allows you to easily configure and manage OpenVPN connections on your computer. OpenVPN is a popular open-source VPN protocol that provides secure and encrypted connections over public networks.

Follow the steps below to download OpenVPN config file along with OpenVPN login credentials.

  1. Log in to your ProtonVPN account at account.protonvpn.com
  2. Go to Downloads tab and then select Platform: Windows and Protocol: UDP and Config File: Free server configs
  3. Click the Action > Download button next to the specific config file you want.
  4. Get your OpenVPN login credentials by visiting Account > OpenVPN / IKEv2 username.
  5. Open the OpenVPN GUI app.
  6. See the icon for OpenVPN GUI appearing in the system tray. Right click on the icon and then go to Import > Import file. OpenVPN
  7. Browse to the location where you saved the downloaded OpenVPN config file and then Click on the Open button.
  8. Right click the OpenVPN GUI icon in system tray and then click on Connect.
  9. It will ask you to enter your OpenVPN login credentials. Enter your username and password and check the Save password box to log in automatically each time.
Python Code

The following code defines a function that executes a command to interact with the OpenVPN GUI. You can connect, disconnect or reconnect the VPN using the code below.

import subprocess

def VPN(action, myvpn=None):
    openvpn_gui_path = r"C:\Program Files\OpenVPN\bin\openvpn-gui.exe"
    
    valid_actions = ["connect", "disconnect", "reconnect", "status"]
    
    if action in valid_actions:
        if myvpn:
            command = f'"{openvpn_gui_path}" --command {action} "{myvpn}"'
        else:
            command = f'"{openvpn_gui_path}" --command {action}'
        
        subprocess.Popen(command, shell=True)
    else:
        print("Invalid action:", action)

myvpn = "us-free-54.protonvpn.net.udp.ovpn"  # Replace with your actual config file
VPN("connect", myvpn)

To disconnect the VPN, use this command VPN("disconnect", myvpn). We have used the subprocess module which provides the ability to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. Install this module if it is not already installed before loading it.

To disable this pop-up do you want to allow this app to make changes to your device? when you run the python script, go to User Account Control Settings and drag the bar slider to "Never notify"

How to Wait till VPN is Connected

Waiting until a VPN is connected before proceeding with certain tasks ensures that a specific portion of your code or a script is executed only when a VPN connection is successfully established. For example, if your code involves web scraping from a region-restricted website or accessing a secure database, you would want to ensure that the VPN is connected before making those requests.

import os
import re
import time

def IPAddress():
    ipconfig = os.popen('ipconfig').read()
    ipv4 = re.findall(r'IPv4.*?(\d+\.\d+\.\d+\.\d+)', ipconfig)
    return ipv4

def WaitUntilVPNConnected():
    s = time.time()
    while len(IPAddress()) == 1:
        time.sleep(3)
        if (time.time() - s) > 15:
            print("VPN not connected")
            break
    if len(IPAddress()) > 1:
        time.sleep(5)
        print("VPN Connected with", IPAddress()[0])

VPN("connect", "us-free-54.protonvpn.net.udp.ovpn")
WaitUntilVPNConnected()
print("testing")
VPN("disconnect", "us-free-54.protonvpn.net.udp.ovpn")

How to Randomly Connect to VPN Locations

The following code introduces randomization when selecting OpenVPN config files and incorporates logging of actions and results into a log file. It is useful in scenarios where you want to avoid being easily identified or tracked based on your IP address. The script generates log entries containing the current date and time, along with appended command outputs. Furthermore, the code verifies the existence of a log file named "proton-log.txt" within the present working directory. In case the file exists, the log entry is added to it. If the file doesn't exist, a new log file is generated.

import os
import random
from datetime import datetime

def proton_random(action, connect_list=None):
    
    # Connect
    openvpn_gui_path = r"C:\Program Files\OpenVPN\bin\openvpn-gui.exe"    
    if connect_list is not None:
        location = random.choice(connect_list) 
        os.popen(f'"{openvpn_gui_path}" --command {action} "{location}"').read()
    
        # Write Log
        log = os.path.join(os.getcwd(), "proton-log.txt")
        log_datetime = f"{datetime.now():%Y-%m-%d %H:%M:%S} {location}"
        log_datetime2 = "\n".join(["", log_datetime])
        if os.path.isfile(log):
            with open(log, "a") as f:
                f.write(log_datetime2)
        else:
            with open(log, "w") as f:
                f.write(log_datetime)
        return(location)
                
    else:
        os.popen(f'"{openvpn_gui_path}" --command {action}')
            

# Connect
connect_list = ["us-free-54.protonvpn.net.udp.ovpn", "us-free-155.protonvpn.net.tcp.ovpn", "vpngate_public-vpn-227.opengw.net_tcp_443.ovpn"]
myvpn = proton_random("connect", connect_list)

# Disconnect
VPN("disconnect", myvpn)
Related Posts
Spread the Word!
Share
About Author:
Deepanshu Bhalla

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and HR.

Post Comment 0 Response to "How to Run Proton VPN in Windows with Python"
Next → ← Prev