69 lines
2.2 KiB
Python
69 lines
2.2 KiB
Python
import psycopg2
|
|
import datetime
|
|
from zoneinfo import ZoneInfo
|
|
|
|
def connect_to_database():
|
|
"""
|
|
Connects to the PostgreSQL database using credentials from 'psql.creds'.
|
|
Returns a connection and cursor object.
|
|
"""
|
|
with open('psql.creds', 'r') as f:
|
|
config = {}
|
|
for line in f:
|
|
key, value = line.strip().split(' = ')
|
|
config[key] = value
|
|
|
|
conn = psycopg2.connect(
|
|
dbname=config['db_name'],
|
|
user=config['db_user'],
|
|
password=config['db_password'],
|
|
host=config['db_host'],
|
|
port=config['db_port']
|
|
)
|
|
cursor = conn.cursor()
|
|
return conn, cursor
|
|
|
|
def should_skip_file(cursor, filename):
|
|
"""
|
|
Checks if the given OVPN file should be skipped based on the last check time in the database.
|
|
Returns True if it should be skipped, False otherwise.
|
|
"""
|
|
try:
|
|
cursor.execute("SELECT last_exit_ip_check FROM ovpn_files WHERE file_name = %s", (filename,))
|
|
row = cursor.fetchone()
|
|
|
|
if row is None:
|
|
print(f"No record found for {filename} in the database.")
|
|
return False # No record found, so don't skip
|
|
|
|
last_check = row[0]
|
|
|
|
if last_check is None: # Handle NULL value
|
|
return False # If last_check is NULL, don't skip
|
|
|
|
# Get current time in UTC timezone using zoneinfo
|
|
now = datetime.datetime.now(tz=ZoneInfo('UTC'))
|
|
|
|
time_difference = now - last_check
|
|
if time_difference.days < 3:
|
|
return True
|
|
return False
|
|
|
|
except psycopg2.Error as e:
|
|
print(f"Error executing database query: {e}")
|
|
return False # In case of an error, don't skip the file
|
|
|
|
|
|
def update_or_insert_ip(cursor, conn, filename, external_ip):
|
|
"""
|
|
Updates or inserts the external IP information for the given OVPN file in the database.
|
|
"""
|
|
cursor.execute("""
|
|
INSERT INTO ovpn_files (file_name, last_observed, last_exit_ip_check, exit_ip)
|
|
VALUES (%s, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, %s)
|
|
ON CONFLICT (file_name) DO UPDATE
|
|
SET last_observed = CURRENT_TIMESTAMP,
|
|
last_exit_ip_check = CURRENT_TIMESTAMP,
|
|
exit_ip = %s
|
|
""", (filename, external_ip, external_ip))
|
|
conn.commit() |