1

I'm trying to write a script to connect to VPN more easily. I want the script to use the user input and connect to a vpn endpoint via openvpn, print the process ID for the user, and then continue running in the background but return the user to the shell. I tried child.close(force=False), os.fork(), and a few other things without any luck. The code I'm using is below. Any advice is much appreciated!

import getpass
import os
import pexpect
import random
import subprocess
import sys

country = sys.argv[1] if len(sys.argv) > 1 else 'US'

print('Connecting to VPN through ' + country)

vpns=subprocess.run(['ls', '/etc/openvpn/'], capture_output=True).stdout.decode().split('\n')
matching_vpns=filter(lambda vpn: vpn[:2].lower() == country.lower(), vpns)

chosen_vpn = random.choice(list(matching_vpns))
print('Connecting to ' + chosen_vpn + '\n')

child = pexpect.spawnu('sudo openvpn /etc/openvpn/'+chosen_vpn)

child.expect('Enter Auth Username:')
username = input('Enter Auth Username: ')
child.sendline(username)
child.expect('Enter Auth Password:')
password = getpass.getpass('Enter Auth Password: ')
child.sendline(password)

child.logfile_read = sys.stdout
while True:
    try:
        child.expect('\n', timeout=None)
        if 'Initialization Sequence Completed' in child.before:
            print("\nSuccessfully connected to " + chosen_vpn)
            print("To stop VPN, run 'sudo pkill -9 -P " + str(child.pid) + "'")
            break
    except pexpect.EOF:
        break
Mason
  • 6,893
  • 15
  • 71
  • 115

0 Answers0