netmiko Documentation

repository·develop·Indexed 26 days ago

https://github.com/ktbyers/netmiko

A multi-vendor Python library designed to simplify legacy CLI connections to network devices. Netmiko abstracts low-level state control and regex pattern matching to facilitate gathering output from show commands and making configuration changes across a wide range of platforms. It provides tools for SSH/Telnet connections via ConnectHandler, support for terminal server redispatching, and encryption handling for sensitive data in YAML configurations.

Tokens
17.9K
Snippets
31
Records
113
Agent score
87%

What's inside netmiko

  1. Access Netmiko Documentation

    develop
    The official Netmiko documentation has moved to GitHub Pages. For general project information and usage instructions, refer to the README. For detailed technical reference and API documentation, use the dedicated documentation site.
  2. Connect using SSH keys or SSH Config files

    develop

    Netmiko supports SSH key-based authentication and the use of local SSH configuration files.

    • SSH Keys: Set use_keys=True and provide the path to your private key in key_file within the device dictionary.
    • SSH Config: Provide the path to your SSH config file using the ssh_config_file key in the device dictionary.
  3. Set up the Netmiko test environment

    develop

    To run the local test suite, you must first initialize the test configuration files by copying the provided examples in the netmiko/tests/etc directory.

    cd ./netmiko/tests/etc  
    cp test_devices.yml.example test_devices.yml  
    cp responses.yml.example responses.yml  
    cp commands.yml.example commands.yml  
  4. Apply configuration changes

    develop

    To apply configuration changes, use send_config_set(commands) for a list of commands or send_config_from_file(filename) to read commands from a file. Netmiko automatically handles entering and exiting configuration mode. After applying changes, remember to save the configuration using the platform-appropriate method (e.g., save_config() for most platforms, or commit() for Cisco-XR, Juniper-Junos, and Palo Alto).

    # Applying a list of commands
    commands = ["logging buffered 100000"]
    with ConnectHandler(**device) as net_connect:
        output = net_connect.send_config_set(commands)
        output += net_connect.save_config()
    
    # Applying from a file
    with ConnectHandler(**device) as net_connect:
        output = net_connect.send_config_from_file("config_changes.txt")
        output += net_connect.save_config()
  5. Configure test devices and responses

    develop

    After copying the example files, you must customize them to define your test parameters:

    1. Edit test_devices.yml

    Select the device_types you wish to test. For each device, provide:

    • ip
    • username
    • password
    • secret (optional)

    2. Edit responses.yml

    For each device_type defined in your devices file, update the following fields to match your test device's behavior:

    • base_prompt
    • router_prompt
    • enable_prompt
    • interface_ip
  6. Handle interactive command prompts using timing

    develop

    If a command triggers a prompt that requires a delay-based response (e.g., a confirmation), use send_command_timing(). This method relies on timing rather than pattern matching. You can use strip_prompt=False and strip_command=False to preserve the full interaction in the output.

    # Example of handling a 'confirm' prompt via timing
    output = net_connect.send_command_timing(
        command_string="del flash:/test3.txt",
        strip_prompt=False,
        strip_command=False
    )
    if "confirm" in output:
        output += net_connect.send_command_timing(
            command_string="y",
            strip_prompt=False,
            strip_command=False
        )
  7. Enable Netmiko logging of all communications

    develop

    To debug communications, you can enable Netmiko logging to capture all reads and writes of the communications channel. This requires configuring the standard Python logging module with a DEBUG level and targeting the netmiko logger.

    import logging
    logging.basicConfig(filename='test.log', level=logging.DEBUG)
    logger = logging.getLogger("netmiko")
  8. Connect via a terminal server using redispatch

    develop

    To connect to an end device through a terminal server, use the terminal_server device_type. Because this type does not automatically handle the terminal server's interaction, you must manually manage the connection (sending commands like connect <id> and handling login prompts) using write_channel() and read_channel(). Once you have successfully reached the end device's prompt, use the redispatch() function to dynamically reset the net_connect object to the correct device type (e.g., cisco_ios) for standard Netmiko operations.

    from __future__ import unicode_literals, print_function
    import time
    from netmiko import ConnectHandler, redispatch
    
    net_connect = ConnectHandler(
        device_type='terminal_server',        # Notice 'terminal_server' here
        ip='10.10.10.10', 
        username='admin', 
        password='admin123', 
        secret='secret123')
    
    # Manually handle interaction in the Terminal Server 
    # (fictional example, but hopefully you see the pattern)
    # Send Enter a Couple of Times
    net_connect.write_channel("\r\n")
    time.sleep(1)
    net_connect.write_channel("\r\n")
    time.sleep(1)
    output = net_connect.read_channel()
    print(output)                             # Should hopefully see the terminal server prompt
    
    # Login to end device from terminal server
    net_connect.write_channel("connect 1\r\n")
    time.sleep(1)
    
    # Manually handle the Username and Password
    max_loops = 10
    i = 1
    while i <= max_loops:
        output = net_connect.read_channel()
        
        if 'Username' in output:
            net_connect.write_channel(net_connect.username + '\r\n')
            time.sleep(1)
            output = net_connect.read_channel()
    
        # Search for password pattern / send password
        if 'Password' in output:
            net_connect.write_channel(net_connect.password + '\r\n')
            time.sleep(.5)
            output = net_connect.read_channel()
            # Did we successfully login
            if '>' in output or '#' in output:
                break
    
        net_connect.write_channel('\r\n')
        time.sleep(.5)
        i += 1
    
    # We are now logged into the end device 
    # Dynamically reset the class back to the proper Netmiko class
    redispatch(net_connect, device_type='cisco_ios')
    
    # Now just do your normal Netmiko operations
    new_output = net_connect.send_command("show ip int brief")
  9. Set the NETMIKO_TOOLS_KEY environment variable

    develop

    Netmiko reads the encryption key from the NETMIKO_TOOLS_KEY environment variable. This key must be a secure, randomly-generated value appropriate for your chosen encryption type (e.g., a Fernet key for fernet encryption).

    export NETMIKO_TOOLS_KEY="your-secure-key-here"
  10. Execute Netmiko tests using pytest

    develop

    Navigate to the netmiko/tests directory to run the test suite. You must specify a --test_device flag, which corresponds to the device name defined in both test_devices.yml and responses.yml.

    Available test scripts:

    • test_netmiko_show.py
    • test_netmiko_config.py
    • test_netmiko_commit.py (Note: currently only supported for Juniper and IOS-XR)
    cd ./netmiko/tests
    
    # Example: testing show commands on a cisco881 device
    py.test -v test_netmiko_show.py --test_device cisco881  
    
    # Example: testing configuration commands on a cisco881 device
    py.test -v test_netmiko_config.py --test_device cisco881