Python Script Stopped Triggering OpenVPN Config Files

39 views Asked by At

I've been scratching my head at this for a few days. The below code worked perfectly fine earlier in the week, but then stopped triggering the OpenVPN Config files it references. Leading the the output csv only containing the headers, with all values returning as blank due to capped IP requests. Open to any ideas.

# Get all .csv files in the directory except for "availability_data.csv"
csv_files = [file for file in glob.glob('*.csv') if file != 'availability_data.csv']

# Get all ProtonVPN Config files in the specified folder
vpn_files = glob.glob('C:/Users/Eruhk/Desktop/Work/Python Scripts/ProtonVPN_server_configs/*.ovpn')

# Function to connect to a random VPN
def connect_vpn():
    vpn_file = random.choice(vpn_files)
    print(f"Connecting to VPN with config file {vpn_file}..")
    subprocess.call([r'C:\Program Files\OpenVPN\bin\openvpn-gui', '--connect', vpn_file])
    time.sleep(10)  # wait for the VPN to connect
    print("Connected to VPN.")

# Function to disconnect from the VPN
def disconnect_vpn():
    print("Disconnecting from VPN...")
    subprocess.call([r'C:\Program Files\OpenVPN\bin\openvpn-gui', '--command', 'disconnect_all'])
    time.sleep(10)  # wait for the VPN to disconnect
    print("Disconnected from VPN.")

# Loop through all .csv files
for csv_file in csv_files:
    # Connect to a random VPN
    connect_vpn()

    # Open the current CSV file and read the data row by row
    with open(csv_file, 'r') as file:
        reader = csv.reader(file)
        next(reader)  # skip header row
        for row in reader:
            # print(row)  # add this line to print out the rows
            sku, zip_code, location_id, *_ = row
            # Update the payload with the current row data
            payload = {
                "locationId": location_id,
                "zipCode": zip_code,
                "showOnShelf": True,
                "lookupInStoreQuantity": True,
                "consolidated": False,
                "showOnlyOnShelf": False,
                "showInStore": True,
                "pickupTypes": ["UPS_ACCESS_POINT", "FEDEX_HAL"],
                "onlyLocations": True,
                "items": items
            }
            items[0]["sku"] = sku  # update the sku in the items list

            # Print current sku/zip
            print(time.strftime("[%H:%M:%S] ") + f"Checking availability for SKU {sku} and zipcode {zip_code}")

            # Send the request and store the response in a variable
            response = requests.post(url, json=payload, headers=headers)

            # Add a random sleep duration between .5-2 seconds before the next query
            sleep_duration = random.randint(1, 2)/10
            time.sleep(sleep_duration)

            # Parse the JSON response and store the relevant data in a dictionary
            parsed_json = json.loads(response.text)

            # Extract all the relevant values from the 'locations' dictionary
            open_times = [location.get('openTimesMap') for location in parsed_json['ispu']['locations']]
            location_format = [location.get('locationFormat').replace("_", " ") for location in parsed_json['ispu']['locations']]
            stock_data = [location.get('availability', {}).get('availablePickupQuantity', 0) for location in parsed_json['ispu']['items'][0]['locations']]
            location_ids = [loc.get('locationId') for item in parsed_json['ispu']['items'] for loc in item['locations']]
            on_shelf_display = [location.get('onShelfDisplay') for item in parsed_json['ispu']['items'] for location in item['locations']]
            addresses = [location.get('address') for location in parsed_json['ispu']['locations']]
            address2 = [location.get('address2') for location in parsed_json['ispu']['locations']]
            cities = [location.get('city') for location in parsed_json['ispu']['locations']]
            states = [location.get('state') for location in parsed_json['ispu']['locations']]
            latitudes = [location.get('latitude') for location in parsed_json['ispu']['locations']]
            longitudes = [location.get('longitude') for location in parsed_json['ispu']['locations']]
            zip_codes = [location.get('zipCode') for location in parsed_json['ispu']['locations']]
            names = [location.get('name') for location in parsed_json['ispu']['locations']]
            today = date.today().strftime("%m/%d/%Y")
            total_location_ids = len(location_ids)

            # Store the availability data in a dictionary
            availability_data = {
                "sku": sku,
                "Store Number": location_ids,
                "Inventory": stock_data,
                "locationFormat": location_format,
                "Date Collected": today
            }

            # Create a DataFrame from the dictionary and append it to a list of data
            data.append(pd.DataFrame.from_dict(availability_data))

    # Disconnect from the VPN
    disconnect_vpn()

Tried added error handling, but since there are no errors actually being thrown, nothing gets printed.

Made sure Python is referencing the correct directories for the config files and OpenVPN-gui.exe.

Edit: Additional detail, running the script with OpenVPN GUI not running results in a popup from OpenVPN GUI: "Cannot find requested config to autostart: C:/Users/Eruhk/Desktop/Work/Python Scripts/ProtonVPN_server_sonfigs\node-us-XXX.protonvpn.net.udp.ovpn"

Running the script with OpenVPN GUI open does not result in any errors, but does not automatically trigger the config files as in the original post.

0

There are 0 answers