Mantra Networking Mantra Networking

Netmiko: ConnectHandler

Netmiko: ConnectHandler
Created By: Lauren R. Garcia

Table of Contents

  • Overview
  • Import Statement
  • Essential Parameters
  • Example Usage
  • Supported Device Types
  • Core Methods
  • Advanced Features
  • Troubleshooting Tips
  • Common Error Scenarios
  • Conclusion

Netmiko: ConnectHandler — Overview

What Is Netmiko: ConnectHandler?

ConnectHandler is the primary interface in the Netmiko Python library for establishing SSH or Telnet connections to a wide range of network devices. Netmiko is designed to simplify and automate operations across multi-vendor environments by abstracting the connection and command execution process, allowing engineers to interact programmatically with routers, switches, firewalls, and other infrastructure platforms.

Why You Need to Know About It

  • Vendor-Agnostic Automation: Most networks run hardware from multiple vendors. ConnectHandler provides a consistent interface to connect to Cisco, Arista, Juniper, HP, Dell, Palo Alto, and many other devices with just a few lines of code.
  • Simplifies Complex Workflows: Rather than manually managing SSH, authentication, privilege escalation, or command parsing for every vendor CLI, Netmiko handles these details automatically.
  • Boosts Productivity: With Netmiko, common tasks such as configuration changes, software upgrades, and operational data retrieval can be automated and scaled with Python scripts—reducing time spent on repetitive manual work.
  • Reduces Human Error: Automation via scripts ensures consistency and accuracy in network tasks, which is critical in large or complex environments.
  • Enables Modern DevOps Practices: If you’re integrating network operations into CI/CD pipelines or infrastructure-as-code workflows, tools like ConnectHandler are foundational for reliable network automation.

How Does It Work?

  1. Device Dictionary Definition:
    You define a Python dictionary specifying the device’s IP/hostname, credentials, type (e.g., Cisco IOS), and any custom connection options.
  2. Connection Establishment:
    Using ConnectHandler, Netmiko opens an SSH or Telnet session to the device, handling authentication and session setup transparently.
  3. Command Execution:
    Once connected, you can programmatically send show commands, configuration commands, or interact with the device using Netmiko’s robust methods (send_commandsend_config_set, etc.).
  4. Privilege Management:
    For devices needing enable/privileged modes, Netmiko allows seamless privilege escalation through optional parameters (secret) and dedicated methods (enable()).
  5. Session Handling:
    After automation tasks are performed, connections can be gracefully closed, and session logging or advanced diagnostics captured as needed.

Netmiko’s ConnectHandler is both approachable for beginners and powerful enough for complex, multi-vendor automation at scale. It’s a fundamental building block for any network professional looking to automate or orchestrate network management tasks efficiently.

Import Statement

Before using Netmiko's ConnectHandler, you need to import the necessary module. This is a straightforward but essential step in preparing your Python environment for network device automation:

  • Step 1: Ensure Netmiko is Installed
    You can install Netmiko using pip if it hasn’t been installed already:
    pip install netmiko
  • Step 2: Import the ConnectHandler Module
    This import gives you access to the main interface used to connect to network devices:
    from netmiko import ConnectHandler
  • Step 3: (Optional) Import Error Handling
    For robust scripts, you may want to import exceptions for handling authentication or timeout issues:
    
    from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException
        

Essential Parameters

To establish a connection to a network device using Netmiko's ConnectHandler, you'll need to provide several essential parameters. Follow these steps to set up your device dictionary:

  • Step 1: Specify the device type
    This tells Netmiko what kind of device you are connecting to (e.g., Cisco IOS, Arista EOS, Juniper Junos).
    "device_type": "cisco_ios"
  • Step 2: Enter the target host or IP
    Define the IP address or hostname of your device.
    "host": "192.168.100.1"
  • Step 3: Provide authentication credentials
    Supply the username and password for device access.
    
    "username": "admin",
    "password": "password123"
        
  • Step 4: (Optional) Enable password/secret
    If your device uses a privilege or enable mode, add the secret.
    "secret": "enablepass"
  • Step 5: (Optional) Set connection options
    Tweak connection behavior as needed, such as specifying an SSH port or enabling verbose output.
    
    "port": 22,
    "verbose": True,
    "global_delay_factor": 2
        

Putting it all together, your device dictionary may look like this:


device = {
    "device_type": "cisco_ios",
    "host": "192.168.100.1",
    "username": "admin",
    "password": "password123",
    "secret": "enablepass",
    "port": 22,
    "verbose": True,
    "global_delay_factor": 2,
}

Only device_type, host, username, and password are strictly required. The rest are optional, depending on your device and connection needs.

Example Usage

The following step-by-step guide demonstrates how to use Netmiko's ConnectHandler to connect to a network device, execute commands, and manage the session:

  • Step 1: Prepare Your Device Dictionary
    Define the parameters needed for your target device. This dictionary includes connection details and login credentials.
    
    device = {
        "device_type": "cisco_ios",
        "host": "192.168.100.1",
        "username": "admin",
        "password": "password123",
        "secret": "enablepass",
        "port": 22,
    }
        
  • Step 2: Establish a Connection
    Use the ConnectHandler to initiate an SSH session to the device.
    
    from netmiko import ConnectHandler
    
    net_connect = ConnectHandler(**device)
        
  • Step 3: Enter Enable Mode (if necessary)
    If your device requires privileged commands, enter enable mode.
    
    net_connect.enable()
        
  • Step 4: Send Commands and Receive Output
    Send a command to the device and capture the output to process or display.
    
    output = net_connect.send_command("show version")
    print(output)
        
  • Step 5: Gracefully Disconnect
    Always close your SSH session once automation tasks are complete.
    
    net_connect.disconnect()
        

This pattern works for most basic Netmiko automation projects. Adjust the command or device details as needed for your use case.

Supported Device Types

Netmiko’s ConnectHandler supports a broad range of network devices from various vendors. To ensure proper communication and behavior, you must use the correct device_type string for your hardware platform. Follow these steps to identify and use supported device types:

  • Step 1: Identify Your Vendor and Platform
    Check the platform (e.g., Cisco IOS, Arista EOS, Juniper Junos) that corresponds to your network device.
    • Cisco: cisco_ios, cisco_xe, cisco_xr, cisco_nxos, cisco_asa
    • Arista: arista_eos
    • Juniper: juniper_junos, juniper_screenos
    • HP: hp_procurve, hp_comware
    • Linux/Unix: linux
    • Dell: dell_os10, dell_os9, dell_powerconnect
    • Huawei: huawei, huawei_olt
    • Palo Alto: paloalto_panos
    • Ubiquiti: ubiquiti_edge, ubiquiti_edgeswitch
    • MikroTik: mikrotik_routeros, mikrotik_switchos
    • Other examples: nokia_sros, f5_ltm, extreme_exos, pluribus, vyos
  • Step 2: Use the Correct device_type String
    When constructing your device dictionary, specify the correct value for device_type:
    
    device = {
        "device_type": "arista_eos",
        "host": "10.1.1.1",
        "username": "admin",
        "password": "password",
    }
        
  • Step 3: (Optional) Explore the Full List
    For less common platforms, Netmiko supports over 80 device types, including those for Telnet and Secure Copy. Consult the official documentation or the module’s platform list if you’re unsure about your specific vendor string.

Many platforms support both SSH and Telnet by changing the device_type (for example, cisco_ios vs cisco_ios_telnet). Be sure to use the string that matches your device and preferred protocol.

Core Methods

Once the SSH connection is established using ConnectHandler, Netmiko provides several useful methods to interact with network devices. Follow this step-by-step breakdown to learn how and when to use each of the core methods:

  • Step 1: send_command()
    Use this method to send a single command (usually a show or non-interactive command) and return its output.
    
    output = net_connect.send_command("show ip interface brief")
    print(output)
        
  • Step 2: send_config_set()
    This method sends one or more configuration commands in global config mode. Often used for making changes to the device.
    
    commands = [
        "interface loopback0",
        "ip address 10.1.1.1 255.255.255.255",
        "no shutdown"
    ]
    output = net_connect.send_config_set(commands)
    print(output)
        
  • Step 3: enable()
    If your device requires enable (privileged exec) mode, this method will elevate the session.
    
    net_connect.enable()
        
  • Step 4: disconnect()
    Properly closes the SSH connection when you're done.
    
    net_connect.disconnect()
        
  • Step 5: find_prompt()
    Returns the current CLI prompt. Useful for debugging or verifying user mode vs privileged mode.
    
    prompt = net_connect.find_prompt()
    print(f"Device prompt: {prompt}")
        
  • Step 6: read_channel()
    Accesses the raw device communication buffer. Typically used in more advanced workflows.
    
    raw_output = net_connect.read_channel()
    print(raw_output)
        

These methods form the foundation of most Netmiko automation workflows. You can combine them to create interactive scripts that manage devices programmatically and reliably.

Advanced Features

Netmiko’s ConnectHandler provides advanced options to make your automation scripts more powerful and robust. Below is a step-by-step breakdown of key advanced features you can leverage:

  • Step 1: Enable Session Logging
    Capture all interactions with a device by creating a session log file. This helps with troubleshooting and auditing.
    
    device = {
        "device_type": "cisco_ios",
        "host": "192.168.100.1",
        "username": "admin",
        "password": "password123",
        "session_log": "my_session.log",  # All session output will be saved here
    }
        
    You can also customize what is redacted in logs by tweaking 'no_log' options via advanced configuration.
  • Step 2: Use SSH Key-based Authentication
    Eliminate passwords by using SSH keys for device authentication. This enhances security and streamlines automation.
    
    device = {
        "device_type": "cisco_ios",
        "host": "192.168.100.1",
        "username": "admin",
        "use_keys": True,
        "key_file": "/path/to/your/private/key",
        # "passphrase": "passphrase_if_key_encrypted"  # Optional
    }
        
  • Step 3: Adjust Delay and Timeout Settings
    Tweak connection behavior for slow devices or high-latency links using these parameters:
    • global_delay_factor: Increases all delays during command execution.
    • timeout: Sets how long to wait for connection or command responses (default is 100 seconds).
    
    device = {
        "global_delay_factor": 2,
        "timeout": 180,
    }
        
  • Step 4: Fast CLI Option
    For supported platforms (such as Cisco IOS), you can enable faster command execution by setting:
    
    device = {
        "fast_cli": True,
    }
        
  • Step 5: Banner and Prompt Handling
    If devices display login banners or have unusual prompts, use:
    • banner_timeout: Increase if your device has a long login banner.
    • session_log: Capture unexpected output for later troubleshooting.
    
    device = {
        "banner_timeout": 50,
        "session_log": "banner_debug.log",
    }
        

These advanced features enable better automation reliability and flexibility. You can combine them as needed to tailor Netmiko behavior for your environment.

Troubleshooting Tips

Even with a solid script, you may encounter issues when using Netmiko’s ConnectHandler. Here’s a step-by-step guide to help diagnose and solve common problems:

  • Step 1: Check Device Connectivity
    Ensure the device is reachable (IP/hostname correct and accessible). Try a manual SSH connection to confirm network access.
    
    ping 192.168.100.1
    ssh admin@192.168.100.1
        
  • Step 2: Verify Credentials and Permissions
    Double-check your username, password, and privilege level. Incorrect credentials are a common cause of authentication errors.
    
    # Common error: NetMikoAuthenticationException
        
  • Step 3: Review Device Type String
    Ensure the device_type matches your platform (e.g., cisco_ios). A typo or unsupported type will trigger errors.
    
    # Common error: ValueError: Unsupported device_type
        
  • Step 4: Increase Delay or Timeout for Slow Devices
    If commands hang or timeout, try raising global_delay_factor or timeout. Some devices (or connections) are slower than others.
    
    device = {
        "global_delay_factor": 2,
        "timeout": 120,
    }
        
  • Step 5: Address Prompt and Output Issues
    If the session hangs or Netmiko fails to detect the device prompt, ensure the prompt ends with the expected character (like # or $), or adjust expect_string or use find_prompt() to debug.
    
    prompt = net_connect.find_prompt()
    print(f"Prompt detected: {prompt}")
        
  • Step 6: Handle Interactive Commands Carefully
    For commands that expect user input (like reload), use send_command_timing() to interact with prompts.
    
    net_connect.send_command("reload", expect_string="confirm")
    net_connect.send_command_timing("Y")
        
  • Step 7: Use Exception Handling for Robust Scripts
    Catch specific exceptions to provide clear error messages and recovery steps.
    
    from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException
    
    try:
        net_connect = ConnectHandler(**device)
    except NetMikoTimeoutException:
        print("Connection timed out – check connectivity and firewall settings.")
    except NetMikoAuthenticationException:
        print("Authentication failed – verify credentials.")
        
  • Step 8: Check for File Name Conflicts
    Ensure your script isn’t named netmiko.py which could cause import issues.
    
    # Common error: ImportError due to script naming conflict
        
  • Step 9: Enable Logging for Debugging
    For persistent or unexplained errors, enable Netmiko logging to get detailed connection and command output.
    
    import logging
    logging.basicConfig(filename='netmiko_debug.log', level=logging.DEBUG)
        

Following these steps will help you troubleshoot and resolve most Netmiko ConnectHandler issues efficiently. Always consult log files and error messages for clues on root causes.

Common Error Scenarios

While working with Netmiko’s ConnectHandler, you may encounter several typical error scenarios. Follow these steps to identify the error, understand its cause, and implement a solution:

  • Step 1: Timeout Errors
    Error: NetMikoTimeoutException
    Cause: Device is unreachable, IP is incorrect, or network/firewall blocks the connection.
    Solution:
    
    # Verify device IP/hostname
    # Check network connectivity (ping and SSH)
    # Confirm firewall allows traffic on the SSH/Telnet port
        
  • Step 2: Authentication Failures
    Error: NetMikoAuthenticationException
    Cause: Wrong username/password or insufficient device privileges.
    Solution:
    
    # Re-enter correct credentials
    # Ensure user account has necessary permissions
        
  • Step 3: Unsupported or Mistyped Device Type
    Error: ValueError: Unsupported device_type
    Cause: Typo or unsupported device type string in your device dictionary.
    Solution:
    
    # Double-check the device_type string (e.g., "cisco_ios")
    # Refer to the list of supported Netmiko platforms
        
  • Step 4: Session Hangs or Unexpected Output
    Error: Script appears stalled or returns incomplete/malformed output.
    Cause: Device needs longer response time or displays a long banner at login.
    Solution:
    
    # Increase global_delay_factor (e.g., set to 2 or 3)
    # Adjust banner_timeout in your device parameters
    # Enable session_log to capture and review output
        
  • Step 5: Import Errors Due to Script Naming
    Error: ImportError: cannot import name 'ConnectHandler'
    Cause: Your script is named netmiko.py, causing import conflicts.
    Solution:
    
    # Rename your script to something other than netmiko.py
    # Remove any old netmiko.pyc files if present
        
  • Step 6: Interactive Command Trouble
    Error: Command expects user input, but script hangs.
    Cause: Sending commands that require confirmation (e.g., reload) without handling input.
    Solution:
    
    # Use send_command_timing() for interactive commands
    # Provide expected responses as arguments in sequence
        

Being familiar with these error patterns will help you quickly identify and resolve most issues when automating with Netmiko’s ConnectHandler. Check logs and error messages for specific details as you troubleshoot.

Conclusion

Throughout this blog post, we explored the core capabilities of Netmiko: ConnectHandler—a powerful tool for simplifying secure and scalable network automation. Here's a quick recap of what we've covered:

  • ✅ Importing Netmiko: A simple import sets the foundation for automating access to network devices.
  • ⚙️ Essential Connection Parameters: Accuracy in your device dictionary is vital—parameters like device_typehostusername, and password are key.
  • 🧪 Example Usage: You learned how to establish a connection, send commands, and disconnect cleanly.
  • 🧩 Supported Device Types: Netmiko supports many platforms including Cisco, Juniper, Arista, HP, Dell, Palo Alto, and others—just use the correct device_type.
  • 🔍 Core Methods: From send_command() to send_config_set(), you now know how to interact with a device programmatically.
  • 🚀 Advanced Features: You can boost performance and flexibility through features like SSH key auth, session logging, and fast_cli mode.
  • 🛠️ Troubleshooting & Error Recovery: We armed you with practical tips on resolving common issues such as authentication failures, timeout errors, and prompt mismatches.

Netmiko’s ConnectHandler is a must-have for any network automation toolkit. Its simplicity combined with deep support for multi-vendor platforms means you can focus more on logic—and less on CLI quirks.

Thanks for following along! Whether you’re just starting out or you’re automating at scale, we hope this guide helped demystify how to use ConnectHandler effectively. Feel free to share your own tips, feedback, or questions in the comments—we’re all learning together.

Happy Automating! 👨‍💻🚀