refactor nord-checker to remove file and sql operations.

This commit is contained in:
2024-09-04 15:47:20 -05:00
parent f1e5e81a7b
commit b725e539a1
3 changed files with 177 additions and 33 deletions
+35 -33
View File
@@ -5,13 +5,16 @@ import time
import datetime
import re
import sys
from psql_utils import connect_to_database, should_skip_file, update_or_insert_ip
from ovpn_downloader import download_and_extract_ovpn_configs
from openvpn_manager import establish_vpn_connection, is_vpn_active, disconnect_vpn, get_external_ip
# Variables
CREDENTIAL_FILE = "nord.creds"
OVPN_DIR = "/root/nordvpn/ovpn_configs/ovpn_tcp"
OVPN_DIR = "/root/nordvpn/ovpn_configs/ovpn_tcp"
LOG_FILE = "/root/nordvpn/openvpn.log"
RESULT_FILE = "vpnlist.txt"
OVPN_ZIP_URL = "https://downloads.nordcdn.com/configs/archives/servers/ovpn.zip"
# Check for debug flag
DEBUG_MODE = False
@@ -29,30 +32,25 @@ print(f"{datetime.datetime.now()} [Main Script]: Current IP before VPN connectio
# Terminate any existing OpenVPN connections
try:
result = subprocess.run(["pgrep", "openvpn"], check=True, capture_output=True)
pids = result.stdout.decode().strip().split('\n')
pids = result.stdout.decode().strip().split('\n') # Get PIDs as a list
for pid in pids:
subprocess.run(["kill", pid])
print(f"{datetime.datetime.now()} [Main Script]: Existing OpenVPN connections terminated.")
except subprocess.CalledProcessError:
pass # No openvpn process found
# Download and extract OVPN configurations
# Download and extract OVPN configurations (using the function from ovpn_downloader.py)
debug_print(f"{datetime.datetime.now()} [Main Script]: Downloading and extracting OVPN configurations...")
if not os.path.exists(OVPN_DIR):
os.makedirs(OVPN_DIR)
subprocess.run(["curl", "-s", "-L", "-o", f"{OVPN_DIR}/ovpn.zip", OVPN_ZIP_URL])
subprocess.run(["unzip", "-q", "-o", f"{OVPN_DIR}/ovpn.zip", "-d", OVPN_DIR])
os.remove(f"{OVPN_DIR}/ovpn.zip")
# Find all OVPN files
ovpn_files = [f for f in os.listdir(OVPN_DIR) if f.endswith(".ovpn")]
ovpn_files = download_and_extract_ovpn_configs() # The function now returns the shuffled list
total_files = len(ovpn_files)
debug_print(f"{datetime.datetime.now()} [Main Script]: Found {total_files} OVPN files to process.")
debug_print(ovpn_files) # Print the list of OVPN files
# Connect to PostgreSQL database
conn, cursor = connect_to_database()
# Process each OVPN file
FILE_NUM = 1
for OVPN_FILE in ovpn_files:
@@ -60,12 +58,21 @@ for OVPN_FILE in ovpn_files:
debug_print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: Processing OVPN file...")
# Check if file exists in database and if last check is older than 3 days
skip_file = should_skip_file(cursor, OVPN_FILENAME)
debug_print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: should_skip_file returned: {skip_file}")
if skip_file:
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: Skipping, last check was less than 3 days ago.")
FILE_NUM += 1
continue
# Read credentials
with open(CREDENTIAL_FILE, 'r') as f:
username = f.readline().strip()
password = f.readline().strip()
debug_print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: Read credentials from {CREDENTIAL_FILE}")
debug_print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: Read credentials: username={username}")
# Establish VPN connection (capture stdout and stderr)
openvpn_command = ["openvpn", "--config", f"{OVPN_DIR}/{OVPN_FILE}",
@@ -97,33 +104,24 @@ for OVPN_FILE in ovpn_files:
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: VPN connection established.")
# Check external IP (with validation and retries)
external_ip = subprocess.check_output(["curl", "-s", "ifconfig.me"]).decode().strip()
external_ip = get_external_ip()
if not re.match(r"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", external_ip):
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: Invalid response from ifconfig.me, retrying with ifconfig.co")
external_ip = subprocess.check_output(["curl", "-s", "ifconfig.co"]).decode().strip()
if not re.match(r"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", external_ip):
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: Invalid response from ifconfig.co, retrying with ipinfo.io/ip")
external_ip = subprocess.check_output(["curl", "-s", "ipinfo.io/ip"]).decode().strip()
if not re.match(r"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", external_ip):
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: Unable to get external IP. Skipping this OVPN file.")
continue
if external_ip is None:
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: Unable to get external IP. Skipping this OVPN file.")
continue
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: External IP via VPN: {external_ip}")
# Append result to file
with open(RESULT_FILE, 'a') as f:
f.write(f"{external_ip} # {OVPN_FILENAME}\n")
# Update or insert into database
update_or_insert_ip(cursor, conn, OVPN_FILENAME, external_ip)
except subprocess.CalledProcessError:
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: VPN connection failed to establish.")
# Disconnect VPN (replace killall with pgrep and kill)
# Disconnect VPN
try:
result = subprocess.run(["pgrep", "openvpn"], check=True, capture_output=True)
pids = result.stdout.decode().strip().split('\n') # Get PIDs as a list
pids = result.stdout.decode().strip().split('\n')
for pid in pids:
subprocess.run(["kill", pid])
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: VPN disconnected.")
@@ -131,10 +129,14 @@ for OVPN_FILE in ovpn_files:
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: No openvpn process found.")
# Wait for a random time between 8 and 30 seconds
sleep_time = random.randint(1, 8)
sleep_time = random.randint(6, 8)
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: Waiting for {sleep_time} seconds before the next connection...")
time.sleep(sleep_time)
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: Resuming...")
# Increment file number
FILE_NUM += 1
FILE_NUM += 1
# Close the database connection
cursor.close()
conn.close()