Netmiko

4.6.0 · active · verified Sun Apr 12

Netmiko is a multi-vendor Python library designed to simplify the process of establishing and managing CLI connections to network devices via SSH, Telnet, or Serial. It handles common networking tasks like sending commands, entering/exiting configuration modes, and transferring files. As of version 4.6.0, Netmiko is actively maintained, frequently adding new device drivers and enhancing existing functionality.

Warnings

Install

Imports

Quickstart

Connects to a network device using credentials from environment variables, sends a 'show ip int brief' command, and attempts to parse the output using TextFSM via `use_textfsm=True`. Remember to configure environment variables like NETMIKO_HOST, NETMIKO_USERNAME, NETMIKO_PASSWORD, and NETMIKO_DEVICE_TYPE before running.

import os
from netmiko import ConnectHandler
from netmiko.exceptions import NetmikoTimeoutException, NetmikoAuthenticationException

# Define device parameters using environment variables for security
device_ip = os.environ.get('NETMIKO_HOST', 'your_device_ip')
username = os.environ.get('NETMIKO_USERNAME', 'your_username')
password = os.environ.get('NETMIKO_PASSWORD', 'your_password')
device_type = os.environ.get('NETMIKO_DEVICE_TYPE', 'cisco_ios') # e.g., cisco_ios, juniper, arista_eos, etc.

if 'your_device_ip' in device_ip or not all([device_ip, username, password, device_type]):
    print("Please set NETMIKO_HOST, NETMIKO_USERNAME, NETMIKO_PASSWORD, and NETMIKO_DEVICE_TYPE environment variables, or update the placeholder values.")
    exit(1)

device = {
    "device_type": device_type,
    "host": device_ip,
    "username": username,
    "password": password,
    # "optional_args": {"port": 22}, # Example for custom SSH port
}

try:
    print(f"Connecting to {device_ip}...")
    with ConnectHandler(**device) as net_connect:
        print("Successfully connected!")
        # Use use_textfsm=True to attempt structured output parsing
        output = net_connect.send_command("show ip int brief", use_textfsm=True)
        print("\n--- Output of 'show ip int brief' (parsed with TextFSM) ---\n")
        print(output)

        # Example for sending configuration commands
        # config_commands = ["interface loopback 0", "ip address 1.1.1.1 255.255.255.255"]
        # output_config = net_connect.send_config_set(config_commands)
        # print("\n--- Configuration Output ---\n")
        # print(output_config)

        net_connect.disconnect()
        print("Disconnected.")

except NetmikoAuthenticationException:
    print("Authentication failed. Check username and password.")
except NetmikoTimeoutException:
    print("Connection timed out. Check host IP and network connectivity.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →