Connecting via VPN in Python

Table of Contents

18 Mar 2023

Exploring how to initiate VPN via Python script. Goal is to connect at the start of a scraping script & disconnect at the end.

Using ProtonVPN on Plus/Unlimited plan - need first to go through CLI tool installation:

See Proton VPN for:

  1. installing the CLI tool
  2. dis/connecting (to) the VPN
  3. CLI commands incl. checking connection status

Functions

Connect

import subprocess

def connect_vpn():
    try:
        # Connect to the fastest available server using sudo
        command = ["sudo", "-S", "protonvpn", "c", "-f"]
        sudo_process = subprocess.Popen(
            command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
        )
        result_stdout, result_stderr = sudo_process.communicate(f"{p}\n")

        if sudo_process.returncode == 0:
            print("✅ Connected to ProtonVPN successfully.")
            return True
        else:
            print("❌ Error connecting to ProtonVPN:")
            print(result_stderr)
            return False
    except Exception as e:
        print(f"❌ An error occurred while trying to connect to ProtonVPN: {e}")
        return False

Disconnect

def disconnect_vpn():
    try:
        # Disconnect from ProtonVPN using sudo
        command = ["sudo", "-S", "protonvpn", "d"]
        sudo_process = subprocess.Popen(
            command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
        )
        result_stdout, result_stderr = sudo_process.communicate(f"{p}\n")

        if sudo_process.returncode == 0:
            print("✅ Disconnected from ProtonVPN successfully.")
            return True
        else:
            print("❌ Error disconnecting from ProtonVPN:")
            print(result_stderr)
            return False
    except Exception as e:
        print(f"❌ An error occurred while trying to disconnect from ProtonVPN: {e}")
        return False

Testing

import my_utils

my_utils.check_my_ip()

print(f"\n\nConnecting VPN...")

my_utils.connect_vpn()

my_utils.wait(7, 10)

my_utils.check_my_ip()

print(f"\n\nDisconnecting VPN...")

my_utils.disconnect_vpn()

my_utils.check_my_ip()

links

social