#!/usr/bin/env python3 import sqlite3 import subprocess import sys from datetime import datetime # --- Configuration --- DB_PATH = '/www/vmail/postfixadmin.db' POSTFIX_RELOAD_COMMAND = ['systemctl', 'restart', 'postfix'] # --------------------- def create_alias(source_email, destination_email): """Inserts the alias into the SQLite database.""" try: # We only validate the source here, as the destination is now hardcoded in __main__ if '@' not in source_email: raise ValueError("Source must be a valid email address.") # Extract the domain name from the source email domain = source_email.split('@')[1] # Connect to the SQLite database # Note: If the database is busy (e.g., mail server is accessing it), this might fail. conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() # Get the current datetime for created/modified fields now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # Check if the alias already exists cursor.execute("SELECT address FROM alias WHERE address=?", (source_email,)) if cursor.fetchone(): print(f"[INFO] Alias {source_email} already exists. Updating its destination...") sql = """ UPDATE alias SET goto = ?, modified = ?, active = 1 WHERE address = ? """ cursor.execute(sql, (destination_email, now, source_email)) else: print(f"[INFO] Creating new alias: {source_email} -> {destination_email}") # SQL statement to insert the new alias # NOTE: We use the schema you provided earlier (no 'id' or 'domain_id') sql = """ INSERT INTO alias (address, goto, domain, created, modified, active) VALUES (?, ?, ?, ?, ?, 1) """ cursor.execute(sql, (source_email, destination_email, domain, now, now)) conn.commit() conn.close() print("[SUCCESS] Database update successful.") return True except ValueError as e: print(f"[ERROR] Input Error: {e}") return False except sqlite3.Error as e: print(f"[ERROR] Database Error: An error occurred connecting to or querying the DB at {DB_PATH}.") print(f"Error details: {e}") return False except Exception as e: print(f"[ERROR] An unexpected error occurred: {e}") return False def reload_postfix(): """Executes the Postfix restart/reload command via subprocess.""" print("[INFO] Attempting to restart Postfix service using systemctl...") try: # Running as root, so no sudo needed, but check=True ensures error detection result = subprocess.run(POSTFIX_RELOAD_COMMAND, check=True, capture_output=True, text=True) if result.returncode == 0: print("[SUCCESS] Postfix restart successful.") else: print(f"[ERROR] Postfix restart failed with code {result.returncode}.") print("Stderr:\n", result.stderr) except subprocess.CalledProcessError as e: print(f"[ERROR] Postfix restart failed. Command returned non-zero exit status.") print(f"Stderr: {e.stderr}") except FileNotFoundError: print(f"[ERROR] Error: Command '{POSTFIX_RELOAD_COMMAND[0]}' not found. Is Postfix installed?") except Exception as e: print(f"[ERROR] An unexpected error occurred during Postfix restart: {e}") if __name__ == "__main__": # Hardcode the desired destination email FIXED_DESTINATION = 'admin@fullpriceexit.com' # We now expect only 2 arguments: the script name and the source email if len(sys.argv) != 2: print("Usage: python3 create_alias.py ") print(f"Note: All created aliases will automatically redirect to {FIXED_DESTINATION}.") print("Example: python3 create_alias.py webmaster@fullpriceexit.com") sys.exit(1) source = sys.argv[1] destination = FIXED_DESTINATION # Use the hardcoded destination # 1. Create the alias in the database if create_alias(source, destination): # 2. Restart Postfix to apply changes reload_postfix() print("\n[COMPLETE] Automation complete.") else: print("\nProcess aborted due to errors.")