refactor away from a log file, stout only.
This commit is contained in:
@@ -3,6 +3,7 @@ import subprocess
|
|||||||
import random
|
import random
|
||||||
import time
|
import time
|
||||||
import datetime
|
import datetime
|
||||||
|
import requests
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
from psql_utils import connect_to_database, update_or_insert_ip
|
from psql_utils import connect_to_database, update_or_insert_ip
|
||||||
@@ -12,10 +13,11 @@ from openvpn_manager import establish_vpn_connection, is_vpn_active, disconnect_
|
|||||||
# Variables
|
# Variables
|
||||||
CREDENTIAL_FILE = "nord.creds"
|
CREDENTIAL_FILE = "nord.creds"
|
||||||
OVPN_DIR = "ovpn_configs/ovpn_tcp"
|
OVPN_DIR = "ovpn_configs/ovpn_tcp"
|
||||||
LOG_FILE = "openvpn.log"
|
LOG_FILE = "openvpn.log" # This is not used anymore
|
||||||
RESULT_FILE = "vpnlist.txt"
|
RESULT_FILE = "vpnlist.txt"
|
||||||
|
PING_URL = "https://health.ext.ben.io/ping/a1a55915-1051-48ed-bd13-ea3f1717a3ee"
|
||||||
|
|
||||||
# Check for debug flag
|
# Define DEBUG_MODE
|
||||||
DEBUG_MODE = False
|
DEBUG_MODE = False
|
||||||
if len(sys.argv) > 1 and sys.argv[1] == "-d":
|
if len(sys.argv) > 1 and sys.argv[1] == "-d":
|
||||||
DEBUG_MODE = True
|
DEBUG_MODE = True
|
||||||
@@ -23,29 +25,58 @@ if len(sys.argv) > 1 and sys.argv[1] == "-d":
|
|||||||
def debug_print(message):
|
def debug_print(message):
|
||||||
if DEBUG_MODE:
|
if DEBUG_MODE:
|
||||||
print(f"{datetime.datetime.now()} + [Debug Mode]:{message}")
|
print(f"{datetime.datetime.now()} + [Debug Mode]:{message}")
|
||||||
else:
|
|
||||||
# log_file.write(f"{datetime.datetime.now()} + [Debug Mode]:{message}\n")
|
|
||||||
log_file.flush() # Flush the buffer to ensure the message is written
|
|
||||||
|
|
||||||
# Open the log file in append mode if not in debug mode
|
try:
|
||||||
log_file = None # Define log_file in the global scope
|
requests.get(PING_URL, timeout=10)
|
||||||
if not DEBUG_MODE:
|
print(f"{datetime.datetime.now()} [Main Script]: Ping sent to: %s" % PING_URL)
|
||||||
log_file = open('nord-checker.log', 'a')
|
except requests.RequestException as e:
|
||||||
# Redirect stdout and stderr to the log file
|
# Log ping failure here...
|
||||||
sys.stdout = log_file
|
print(f"{datetime.datetime.now()} [Main Script]: Ping failed: %s" % e)
|
||||||
sys.stderr = log_file
|
|
||||||
|
# Function to check if the script is already running
|
||||||
|
def is_script_running():
|
||||||
|
"""Checks if another instance of the script is already running."""
|
||||||
|
try:
|
||||||
|
# Use pgrep to find processes with the exact command line of the script
|
||||||
|
command_line = f"/usr/bin/python3 {os.path.abspath(__file__)} >> /var/log/nord-checker.log 2>&1" # Include redirection
|
||||||
|
process = subprocess.run(["pgrep", "-f", command_line],
|
||||||
|
capture_output=True, text=True)
|
||||||
|
|
||||||
|
# If pgrep finds any matches, it means the script is already running
|
||||||
|
if process.returncode == 0 and process.stdout:
|
||||||
|
# Get the PIDs of the running instances
|
||||||
|
pids = [int(pid) for pid in process.stdout.strip().split("\n")]
|
||||||
|
|
||||||
|
# Exclude the current process's PID
|
||||||
|
pids = [pid for pid in pids if pid != os.getpid()]
|
||||||
|
|
||||||
|
# Only quit if there are two or more other instances running
|
||||||
|
if len(pids) >= 2:
|
||||||
|
for pid in pids:
|
||||||
|
try:
|
||||||
|
# Get the CMD value using ps
|
||||||
|
process_info = subprocess.check_output(["ps", "-o", "cmd=", "-p", str(pid)], text=True).strip()
|
||||||
|
print(f"{datetime.datetime.now()} [Main Script]: Another instance of the script is already running (PID: {pid}): {process_info}")
|
||||||
|
except subprocess.CalledProcessError:
|
||||||
|
print(f"{datetime.datetime.now()} [Main Script]: Another instance of the script is already running (PID: {pid}), but unable to retrieve process information.")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f"{datetime.datetime.now()} [Main Script]: Error checking for running instances: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Get current IP before starting (using get_external_ip)
|
# Get current IP before starting (using get_external_ip)
|
||||||
CURRENT_IP = get_external_ip()
|
CURRENT_IP = get_external_ip()
|
||||||
if CURRENT_IP is None:
|
if CURRENT_IP is None:
|
||||||
print(f"{datetime.datetime.now()} [Main Script]: Unable to get current IP. Exiting.")
|
print(f"{datetime.datetime.now()} [Main Script]: Unable to get current IP. Exiting.")
|
||||||
if not DEBUG_MODE:
|
|
||||||
log_file.close() # Close the log file if it was opened
|
|
||||||
sys.exit(1) # Exit if unable to get current IP
|
sys.exit(1) # Exit if unable to get current IP
|
||||||
else:
|
else:
|
||||||
print(f"{datetime.datetime.now()} [Main Script]: Current IP before VPN connections: {CURRENT_IP}")
|
print(f"{datetime.datetime.now()} [Main Script]: Current IP before VPN connections: {CURRENT_IP}")
|
||||||
if not DEBUG_MODE:
|
|
||||||
log_file.flush()
|
if is_script_running():
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
# Terminate any existing OpenVPN connections
|
# Terminate any existing OpenVPN connections
|
||||||
try:
|
try:
|
||||||
@@ -54,8 +85,6 @@ try:
|
|||||||
for pid in pids:
|
for pid in pids:
|
||||||
subprocess.run(["kill", pid])
|
subprocess.run(["kill", pid])
|
||||||
print(f"{datetime.datetime.now()} [Main Script]: Existing OpenVPN connections terminated.")
|
print(f"{datetime.datetime.now()} [Main Script]: Existing OpenVPN connections terminated.")
|
||||||
if not DEBUG_MODE:
|
|
||||||
log_file.flush()
|
|
||||||
except subprocess.CalledProcessError:
|
except subprocess.CalledProcessError:
|
||||||
pass # No openvpn process found
|
pass # No openvpn process found
|
||||||
|
|
||||||
@@ -123,22 +152,16 @@ for OVPN_FILE in ovpn_files_to_check:
|
|||||||
# Disconnect VPN
|
# Disconnect VPN
|
||||||
disconnect_vpn()
|
disconnect_vpn()
|
||||||
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: VPN disconnected.")
|
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: VPN disconnected.")
|
||||||
if not DEBUG_MODE:
|
|
||||||
log_file.flush()
|
|
||||||
# Wait for a random time between 5 and 8 seconds
|
# Wait for a random time between 5 and 8 seconds
|
||||||
sleep_time = random.randint(5, 8)
|
sleep_time = random.randint(5, 8)
|
||||||
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: Waiting for {sleep_time} seconds before the next connection...")
|
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: Waiting for {sleep_time} seconds before the next connection...")
|
||||||
time.sleep(sleep_time)
|
time.sleep(sleep_time)
|
||||||
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: Resuming...")
|
print(f"{datetime.datetime.now()} [{FILE_NUM}/{total_files}] [{OVPN_FILENAME}]: Resuming...")
|
||||||
if not DEBUG_MODE:
|
|
||||||
log_file.flush()
|
|
||||||
# Increment file number
|
# Increment file number
|
||||||
FILE_NUM += 1
|
FILE_NUM += 1
|
||||||
|
|
||||||
# Close the database connection
|
# Close the database connection
|
||||||
cursor.close()
|
cursor.close()
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
# Close the log file if it was opened
|
|
||||||
if not DEBUG_MODE:
|
|
||||||
log_file.close()
|
|
||||||
@@ -16,7 +16,7 @@ def establish_vpn_connection(ovpn_file, credential_file, log_file, debug_print=N
|
|||||||
password = f.readline().strip()
|
password = f.readline().strip()
|
||||||
|
|
||||||
# Establish VPN connection (capture stdout and stderr)
|
# Establish VPN connection (capture stdout and stderr)
|
||||||
openvpn_command = ["openvpn", "--config", ovpn_file,
|
openvpn_command = ["/usr/sbin/openvpn", "--config", ovpn_file,
|
||||||
"--auth-user-pass", credential_file,
|
"--auth-user-pass", credential_file,
|
||||||
"--verb", "1"]
|
"--verb", "1"]
|
||||||
|
|
||||||
@@ -41,8 +41,11 @@ def establish_vpn_connection(ovpn_file, credential_file, log_file, debug_print=N
|
|||||||
debug_print(f"OpenVPN exited with a non-zero return code: {process.returncode}")
|
debug_print(f"OpenVPN exited with a non-zero return code: {process.returncode}")
|
||||||
return False, process.stderr.read().decode()
|
return False, process.stderr.read().decode()
|
||||||
|
|
||||||
# Read a line from stdout (non-blocking)
|
try:
|
||||||
line = process.stdout.readline().decode()
|
line = process.stdout.readline().decode()
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
print(f"Decoding error: {line.strip()}") # Log the problematic line
|
||||||
|
continue # Skip to the next line
|
||||||
if line:
|
if line:
|
||||||
if debug_print:
|
if debug_print:
|
||||||
debug_print(f"OpenVPN output: {line.strip()}")
|
debug_print(f"OpenVPN output: {line.strip()}")
|
||||||
|
|||||||
Reference in New Issue
Block a user