Mantra Networking Mantra Networking

Netmiko: Command Execution Methods

Netmiko: Command Execution Methods
Created By: Lauren R. Garcia

Table of Contents

  • Overview
  • Method Descriptions and Usage
  • Output Handling & Best Practices
  •  Example Snippets
  •  Reference Table: Method Selection
  • Conclusion

Netmiko Command Execution Methods: Overview

What Is Netmiko?

Netmiko is an open-source Python library designed to simplify connecting to network devices over SSH, sending commands, and automating a wide variety of network management tasks. It provides a unified interface to interact with devices from numerous vendors such as Cisco, Arista, Juniper, and more. Its robust framework saves time for network engineers by abstracting the differences between device platforms and handling common communication challenges, including authentication, prompt detection, and error handling.

Why You Need to Know About Netmiko Command Execution Methods

  • Automate Tedious Tasks: Traditional network management via the command line can be repetitive and error-prone. Netmiko allows you to automate these routine tasks, leading to faster deployments, consistent configurations, and reduced risk of mistakes.
  • Multi-Vendor Support: Managing a modern infrastructure often means working with devices from different vendors. Netmiko bridges these differences with a consistent Pythonic interface.
  • Scalability: For large-scale environments with hundreds or thousands of devices, manually executing commands is impractical. Netmiko enables scripts that can audit, configure, or troubleshoot multiple devices efficiently.
  • Integrates With Other Tools: Netmiko plays well with Python-based automation frameworks, making it easy to integrate into broader workflows for tasks like compliance checking, asset inventory, or device monitoring.

How Netmiko Command Execution Works

  • Establishes SSH Sessions: Using device credentials and parameters, Netmiko creates secure SSH connections to the target devices without requiring manual logins.
  • Flexible Command Methods: Netmiko offers multiple methods for sending commands—including single commands, batches of show commands, sets of configuration changes, or even commands read from files. Each method is designed for a specific use case, allowing you to tailor your automation scripts for precision and efficiency.
  • Handles Vendor Nuances: The library automatically handles differences such as command prompt variations, configuration contexts, and session terminations across vendor platforms.
  • Parses and Returns Output: Command responses are returned as plain text or structured data (with TextFSM). You can capture, log, or further process this data for reporting, alerting, or validation.
  • Manages Sessions and Errors: Netmiko provides built-in error checking, timeout handling, and graceful session cleanup, which are essential for reliable automation.

Understanding Netmiko’s command execution methods is foundational for anyone looking to automate network administration, support continuous integration pipelines, or improve operational efficiency in network management. With these methods, you can transform how you approach device provisioning, compliance, diagnostics, and change management.

Method Descriptions and Usage

This section breaks down each Netmiko command execution method, its use-cases, parameters, and basic usage patterns to help you automate network tasks efficiently:

  • send_command()
    • Purpose: Execute a single command (e.g., "show version") and return the device’s response as a string.
    • Common Parameters:
      • command_string: The CLI command to execute.
      • expect_string (optional): Regex to define expected CLI prompt or output.
      • delay_factor (optional): Increase wait times for slow responses.
      • use_textfsm (optional): Parse structured output with TextFSM templates.
    • Best Use: Gathering device status, running quick checks, collecting output for parsing or logging.
    • Example:
      output = net_connect.send_command("show ip int brief")
  • send_config_set()
    • Purpose: Send a list or set of configuration commands to the device’s config mode.
    • Common Parameters:
      • config_commands: List of CLI configuration commands.
      • exit_config_mode (optional): Exit config mode after commands (default: True).
      • delay_factor (optional): For slow connections/devices.
    • Best Use: Applying batch network changes, interface or VLAN config, templated deployments.
    • Example:
      config = [
          "interface GigabitEthernet1",
          "description Automated by Netmiko",
          "no shutdown"
      ]
      output = net_connect.send_config_set(config)
  • send_config_from_file()
    • Purpose: Read configuration commands from a local file and apply to the device.
    • Common Parameters:
      • config_file: File path containing CLI config commands.
      • exit_config_mode, delay_factor: Same options as send_config_set().
    • Best Use: Large-scale deployments, versioned configs, repeatable device setups.
    • Example:
      output = net_connect.send_config_from_file("router_config.txt")
  • send_multiline()
    • Purpose: Send a block of commands or multi-line string as a single interaction.
    • Common Parameters:
      • commands: Multi-line string or list of commands.
      • strip_prompt, strip_command (optional): Remove extra CLI prompt/echo from output.
    • Best Use: When a single configuration context requires multiple commands in order (e.g., banners, access-lists).
    • Example:
      output = net_connect.send_multiline(commands="banner motd ^\nUnauthorized access prohibited\n^")
  • send_command_timing()
    • Purpose: Executes a command and waits a predefined time rather than relying on prompt or pattern-matching.
    • Common Parameters:
      • command_string: The CLI command to run.
      • delay_factor: Adjust timing as needed.
    • Best Use: For devices with unreliable prompt patterns or when precise timing is crucial.
    • Example:
      output = net_connect.send_command_timing("reload")
  • send_commands()
    • Purpose: Send a list of commands for sequential execution and aggregate all results.
    • Common Parameters:
      • commands: List of CLI commands.
      • use_textfsm (optional): Parse each output using TextFSM.
      • delay_factor (optional): Adjust for device/connections speed.
    • Best Use: Bulk retrieval of device state (“show” commands), audits, automations requiring multiple data points.
    • Example:
      output = net_connect.send_commands(commands=["show version", "show users", "show inventory"])
Output Handling & Best Practices

This section outlines effective strategies and best practices for working with Netmiko command outputs in production network automation:

  • 1. Structured Parsing with TextFSM
    • Use the use_textfsm=True parameter with send_command() or send_commands() to transform raw command output into structured Python dictionaries or lists for easier data analysis.
    • Utilize official or custom TextFSM templates for commonly used CLI commands to streamline parsing and avoid manual text manipulation.
    • Example:
      output = net_connect.send_command("show interfaces status", use_textfsm=True)
  • 2. Output Paging Considerations
    • Ensure output is not truncated due to device paging settings. Disable paging on the device (e.g., terminal length 0 on Cisco IOS) prior to sending commands to capture the entire output in one call.
    • For devices with nonstandard paging behavior, consider sending specific CLI commands to disable output paging before main operational queries.
  • 3. Error Handling for Config Commands
    • Implement robust error handling using try/except blocks for common failures such as timeouts and authentication errors. Always handle exceptions like NetmikoTimeoutException and NetmikoAuthenticationException directly.
    • For send_config_set(), use the error_pattern argument to detect specific errors in config output and halt further execution if errors occur.
    • Example:
      try:
          output = net_connect.send_config_set(config_commands, error_pattern=r"% Invalid input")
      except Exception as error:
          print("Configuration change failed:", error)
      
  • 4. Adjusting for Device Timing
    • Use the delay_factor parameter when working with slow or high-latency devices to avoid incomplete responses or premature timeouts. Increase the delay as needed to account for device responsiveness.
    • Tip: Set delay_factor=2 or higher for long-running commands or devices with slow processing.
  • 5. Validating Output
    • Always assess the returned output for signs of errors or incomplete data, especially after configuration changes. Search for known error strings, such as % Invalid input or ERROR, in the response.
    • For outputs with sensitive or critical data, validate responses with regular expressions or through cross-checking expected patterns.
  • 6. Clean Presentation and Post-Processing
    • Remove any extra CLI prompts or echoed commands from output for clarity. Use parameters like strip_prompt and strip_command when available.
    • For advanced needs, further process output into lists or dictionaries using Python's splitlines(), split(), or regular expressions.
  • 7. Logging and Record-Keeping
    • Store outputs for each command execution to external files or logging systems. This approach supports auditing, troubleshooting, and change management.
    • Log both the commands sent and their corresponding responses for comprehensive traceability.
Example Snippets

The following code samples show practical usage of Netmiko’s most common command execution methods in automation workflows:

  • Connect to a Device
    from netmiko import ConnectHandler
    
    device = {
        "device_type": "cisco_ios",
        "host": "192.0.2.1",
        "username": "admin",
        "password": "password",
    }
    net_connect = ConnectHandler(**device)
    
  • Execute a Single Show Command
    # Get interface status
    output = net_connect.send_command("show ip interface brief")
    print(output)
    
  • Run Multiple Show Commands and Aggregate Results
    commands = ["show version", "show inventory"]
    output = net_connect.send_commands(commands)
    for cmd, result in output.items():
        print(f"--- {cmd} ---\n{result}")
    
  • Send a Set of Configuration Commands
    config_commands = [
        "interface GigabitEthernet1",
        "description Configured by Netmiko",
        "no shutdown"
    ]
    output = net_connect.send_config_set(config_commands)
    print(output)
    
  • Apply Configuration from a File
    output = net_connect.send_config_from_file("config.txt")
    print(output)
    
  • Send a Multi-Line Command Block
    banner = "banner motd ^\nUnauthorized Access Prohibited\n^"
    output = net_connect.send_multiline(commands=banner)
    print(output)
    
  • Handle Output Parsing with TextFSM
    output = net_connect.send_command("show interfaces status", use_textfsm=True)
    for entry in output:
        print(entry)
    
  • Disconnect from Device
    net_connect.disconnect()
    
Reference Table: Method Selection

This table summarizes recommended Netmiko command execution methods based on different automation scenarios. Use this as a quick guide to select the optimal method for your specific needs:

Scenario Recommended Method Description
Single show/exec command send_command() Runs one CLI command and returns the output as a string.
Batch show commands send_commands() Executes a list of show or exec commands and aggregates results for each.
Small set of configuration changes send_config_set() Pushes a list of configuration commands; has error checking and context handling.
Large configuration file deployment send_config_from_file() Reads config from a file and applies it line by line.
Multi-line/advanced config block send_multiline() Sends multiple lines or a single block as one interaction.
Unpredictable CLI prompt situations send_command_timing() Executes commands using timing instead of prompt detection.

Refer to this table when selecting methods in your automation scripts to optimize reliability and maintainability.

Conclusion: Netmiko Command Execution Methods

Throughout this blog post, we explored the essential command execution methods provided by the Netmiko library and how they apply to real-world network automation tasks. Here’s a quick recap of what we’ve covered:

🔑 Main Takeaways:

  • Netmiko simplifies multi-vendor CLI interactions by abstracting the connection, authentication, and command execution processes.
  • The send_command() method is excellent for quick data collection like "show" outputs.
  • Use send_config_set() and send_config_from_file() to push configurations efficiently—ideal for change control and scripted deployments.
  • The send_multiline() method is useful for more complex or nested configuration blocks (e.g., banners or multiline ACLs).
  • When CLI prompts are inconsistent, send_command_timing() offers greater control by bypassing prompt matching.
  • TextFSM and output handling strategies help turn raw device output into structured data for easy parsing, validation, and logging.
  • reference method table was provided to assist with choosing the right method for the specific task at hand.

By mastering these methods, you’ll be better equipped to build scalable, idempotent automation solutions using Python and Netmiko, saving time and reducing human error during device provisioning, monitoring, and configuration.

Thanks for joining us on this deep dive into Netmiko’s command execution methods! Whether you’re automating a few switches or managing infrastructure at scale, we hope these tools and examples help boost your efficiency and confidence. 💻⚙️

Happy automating! 🚀