import psycopg2 from datetime import datetime # Read database connection details from psql.creds db_config = {} try: with open('psql.creds', 'r') as f: for line in f: if '=' not in line: continue key, value = line.strip().split('=') db_config[key.strip()] = value.strip() except FileNotFoundError: print("Error: psql.creds file not found. Please make sure it exists in the same directory as the script.") exit(1) # Initialize counters for the summary total_processed = 0 successful_updates = 0 try: # Connect to the PostgreSQL database using the config conn = psycopg2.connect( dbname=db_config['db_name'], user=db_config['db_user'], password=db_config['db_password'], host=db_config['db_host'], port=db_config['db_port'] ) cur = conn.cursor() # Read the file line by line with open('vpnlist.txt', 'r') as f: for line_number, line in enumerate(f, start=1): if line.startswith('#'): continue if ' # ' not in line: print(f"Skipping invalid line {line_number}: {line}") continue try: parts = line.strip().split(' # ') exit_ip = parts[0] file_name = parts[1].strip() except IndexError: print(f"Error parsing line {line_number}: {line}") continue total_processed += 1 # Update the database current_timestamp = datetime.now() cur.execute( """ UPDATE ovpn_files SET exit_ip = %s, last_exit_ip_check = %s WHERE file_name = %s """, (exit_ip, current_timestamp, file_name) ) successful_updates += cur.rowcount # Commit the changes to the database conn.commit() # Print the summary print(f"Processed {total_processed} files. Successfully updated {successful_updates} rows in the database.") except (Exception, psycopg2.DatabaseError) as error: print(f"Error connecting to the database: {error}") finally: if conn is not None: cur.close() conn.close()