|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Script runner that executes multiple Python scripts in sequence. |
| 4 | +This module provides functionality to run multiple Python scripts in order, |
| 5 | +with comprehensive logging of execution results. |
| 6 | +""" |
| 7 | + |
| 8 | +import subprocess |
| 9 | +import sys |
| 10 | +import os |
| 11 | +import logging |
| 12 | +from datetime import datetime |
| 13 | +from typing import List |
| 14 | + |
| 15 | +# Define the directory for logs and scripts |
| 16 | +SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) |
| 17 | +LOG_DIR = os.path.join(SCRIPT_DIR, 'logs') |
| 18 | + |
| 19 | +# Ensure the log directory exists |
| 20 | +os.makedirs(LOG_DIR, exist_ok=True) |
| 21 | + |
| 22 | +def setup_logging() -> logging.Logger: |
| 23 | + """ |
| 24 | + Configure logging with both file and console handlers. |
| 25 | +
|
| 26 | + Returns: |
| 27 | + logging.Logger: Configured logger instance |
| 28 | + """ |
| 29 | + # Create logger |
| 30 | + logger = logging.getLogger(__name__) |
| 31 | + logger.setLevel(logging.DEBUG) |
| 32 | + |
| 33 | + # Create formatters |
| 34 | + file_formatter = logging.Formatter( |
| 35 | + '%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s' |
| 36 | + ) |
| 37 | + console_formatter = logging.Formatter( |
| 38 | + '%(asctime)s - %(levelname)s - %(message)s' |
| 39 | + ) |
| 40 | + |
| 41 | + # Create file handlers |
| 42 | + timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') |
| 43 | + debug_handler = logging.FileHandler( |
| 44 | + os.path.join(LOG_DIR, f'script_execution_debug_{timestamp}.log') |
| 45 | + ) |
| 46 | + debug_handler.setLevel(logging.DEBUG) |
| 47 | + debug_handler.setFormatter(file_formatter) |
| 48 | + |
| 49 | + error_handler = logging.FileHandler( |
| 50 | + os.path.join(LOG_DIR, f'script_execution_error_{timestamp}.log') |
| 51 | + ) |
| 52 | + error_handler.setLevel(logging.ERROR) |
| 53 | + error_handler.setFormatter(file_formatter) |
| 54 | + |
| 55 | + # Create console handler |
| 56 | + console_handler = logging.StreamHandler() |
| 57 | + console_handler.setLevel(logging.INFO) |
| 58 | + console_handler.setFormatter(console_formatter) |
| 59 | + |
| 60 | + # Add handlers to logger |
| 61 | + logger.addHandler(debug_handler) |
| 62 | + logger.addHandler(error_handler) |
| 63 | + logger.addHandler(console_handler) |
| 64 | + |
| 65 | + return logger |
| 66 | + |
| 67 | +def run_script(script_name: str, logger: logging.Logger) -> bool: |
| 68 | + """ |
| 69 | + Executes a Python script using the current Python interpreter. |
| 70 | +
|
| 71 | + Args: |
| 72 | + script_name (str): The name of the script to run. |
| 73 | + logger (logging.Logger): The logger instance for logging messages. |
| 74 | +
|
| 75 | + Returns: |
| 76 | + bool: True if the script runs successfully, False otherwise. |
| 77 | + """ |
| 78 | + logger.info(f"Running {script_name}...") |
| 79 | + |
| 80 | + try: |
| 81 | + # Run the script using the current Python interpreter |
| 82 | + result = subprocess.run( |
| 83 | + [sys.executable, script_name], |
| 84 | + capture_output=True, |
| 85 | + text=True, |
| 86 | + check=True |
| 87 | + ) |
| 88 | + logger.info(f"{script_name} completed successfully.") |
| 89 | + logger.debug(f"Output:\n{result.stdout}") |
| 90 | + return True |
| 91 | + except subprocess.CalledProcessError as e: |
| 92 | + logger.error(f"Error running {script_name}:") |
| 93 | + logger.error(e.stderr) # Log the error message if the script fails |
| 94 | + return False |
| 95 | + |
| 96 | +def main(): |
| 97 | + """ |
| 98 | + Main function to run a list of Python scripts sequentially. |
| 99 | +
|
| 100 | + The function will stop execution if any script fails, preventing subsequent |
| 101 | + scripts from running if an error is encountered. |
| 102 | + """ |
| 103 | + logger = setup_logging() |
| 104 | + |
| 105 | + # List of scripts to execute in order |
| 106 | + scripts: List[str] = [ |
| 107 | + "netbox_export.py", |
| 108 | + "network_scan.py", |
| 109 | + "scan_processor.py", |
| 110 | + "netbox_import.py" |
| 111 | + ] |
| 112 | + |
| 113 | + # Iterate over the list of scripts and run each one |
| 114 | + for script in scripts: |
| 115 | + if not run_script(script, logger): |
| 116 | + logger.error(f"Execution stopped due to an error in {script}") |
| 117 | + break # Stop execution if a script fails |
| 118 | + else: |
| 119 | + logger.info("All scripts executed successfully.") |
| 120 | + |
| 121 | +if __name__ == "__main__": |
| 122 | + # Run the main function if the script is executed directly |
| 123 | + main() |
0 commit comments