Running multiple commands based on options

#!/usr/bin/env python3
"""
Guestshell-friendly multiple config and show commands.

Usage:
  python3 multicmds.py -c configcmds.txt -f cfdown (match the config secion in configcmds.txt)
  python3 multicmds.py -s showcmds.txt (list of commands to run)

Output:
  output of commands
"""
import sys
import os
import cli
import argparse
from datetime import datetime

# Derive log file name from the script name
SCRIPT_NAME = os.path.basename(sys.argv[0])       # e.g. "change_tunnel_ip.py"
LOG_FILE = os.path.splitext(SCRIPT_NAME)[0] + ".log"  # -> "change_tunnel_ip.log"

def log(message):
    with open(LOG_FILE, "a") as f:
        f.write(f"{datetime.now()}: {message}\n")

def load_config(config_file, flag):
    """Parse config file and return list of commands for given flag."""
    commands = []
    current_flag = None
    try:
        with open(config_file) as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith("#"):
                    continue
                if line.startswith("[") and line.endswith("]"):
                    current_flag = line[1:-1]
                    continue
                if current_flag == flag:
                    commands.append(line)
    except FileNotFoundError:
        log(f"Config file {config_file} not found.")
    return commands

def load_show_file(show_file):
    """Load commands directly from a file containing show command(s)."""
    commands = []
    try:
        with open(show_file) as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith("#"):
                    continue
                commands.append(line)
    except FileNotFoundError:
        log(f"Show file {show_file} not found.")
    return commands

def main():
    parser = argparse.ArgumentParser(description="Apply tunnel config or run show commands")
    parser.add_argument("-c", "--config", help="Path to config file with flag sections")
    parser.add_argument("-f", "--flag", help="Flag to apply (must match section in config file)")
    parser.add_argument("-s", "--showfile", help="File containing show command(s) to run directly")

    args = parser.parse_args()

    commands = []
    mode = None

    if args.showfile:
        commands = load_show_file(args.showfile)
        mode = "show"
    elif args.config and args.flag:
        commands = load_config(args.config, args.flag)
        mode = "config"
    else:
        print("Usage: script.py -c <config_file> -f <flag> OR script.py -s <show_file>")
        return

    if not commands:
        print("No commands found to apply.")
        return

    try:
        if mode == "config":
            cli.configure(["configure terminal"] + commands + ["end"])
            print(f"Config commands for flag '{args.flag}' applied successfully.")
            log(f"Config commands for flag '{args.flag}' applied successfully.")
        elif mode == "show":
            for cmd in commands:
                output = cli.cli(cmd)
                print(f"\n--- Output of '{cmd}' ---\n{output}\n")
                log(f"Ran show command: {cmd}")
    except Exception as e:
        print(f"Error while applying commands: {e}")
        log(f"Error while applying commands: {e}")

if __name__ == "__main__":
    main()

Config commands

Show Commands

Last updated