chatgpt generated

write me a script that rotates though all openvpn config files with an auth file, stops openvpn after each config rotation, makes sure no connection is ever used twice and waits 10 seconds before initializing a new connection avatar
a year ago
2.0 kB
import os
import time
import random
import subprocess

# Define the directory where OpenVPN config files are located
config_dir = '/path/to/config/files/'

# Define the path to the OpenVPN authentication file
auth_file = '/path/to/auth/file'

# Get a list of all OpenVPN config files in the directory
config_files = os.listdir(config_dir)
config_files = [file for file in config_files if file.endswith('.ovpn')]

# Shuffle the list of config files to ensure that no connection is ever used twice

# Define an empty list to store the used config files
used_configs = []

# Define the OpenVPN command to use
openvpn_cmd = 'openvpn'

# Define the options to use with the OpenVPN command
openvpn_options = ['--auth-user-pass', auth_file]

# Loop through the config files and rotate the connection
for config_file in config_files:
    # If all config files have been used, reshuffle the list and start again
    if len(used_configs) == len(config_files):
        used_configs = []
    # Check if the current config file has been used before
    while config_file in used_configs:
        config_file = random.choice(config_files)
    # Add the current config file to the list of used config files
    print('Switching to ' + config_file)
    # Update the OpenVPN options to use the current config file
    openvpn_options += ['--config', os.path.join(config_dir, config_file)]
    # Start the OpenVPN connection
    openvpn_process = subprocess.Popen([openvpn_cmd] + openvpn_options)
    # Wait for 10 seconds to give OpenVPN time to start up
    # Send a SIGTERM signal to the OpenVPN process to stop the connection
    # Wait for 10 seconds to give OpenVPN time to close the connection
    # Clear the current config file from the OpenVPN options
    openvpn_options = openvpn_options[:-2]