Netmiko Ssh Automation 标志

Netmiko Ssh Automation

社区
arsallls
netmiko-ssh-automation

Multi-vendor network device SSH automation using Python Netmiko — connecting, sending commands, parsing output, handling enable mode, error handling, and batch operations across device lists.

Add to TypingMind

概览

发布者arsallls
代码仓库claude-network-skills
技能名称netmiko-ssh-automation
星标数
77
复刻数
14
附带文件
仅含指令
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 arsallls 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Netmiko Ssh Automation AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/arsallls/claude-network-skills/tree/main/skills/netmiko-ssh-automation
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/arsallls/claude-network-skills.git /tmp/claude-network-skills
mkdir -p .claude/skills
cp -r /tmp/claude-network-skills/skills/netmiko-ssh-automation .claude/skills/netmiko-ssh-automation
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Netmiko Ssh Automation,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Netmiko Ssh Automation。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Netmiko Ssh Automation 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Netmiko SSH Automation

Patterns for automating network device interaction via SSH using Netmiko. Covers single-device connections, batch operations, enable mode, error handling, and output parsing.

When to Activate

  • Writing Python scripts to automate Cisco, Juniper, Arista, or other network devices via SSH
  • Collecting show command output from multiple devices programmatically
  • Applying configuration changes across a fleet of devices
  • Parsing structured or semi-structured CLI output in Python
  • Building network automation tools or scripts that talk to real devices

Basic Connection

python
from netmiko import ConnectHandler

device = {
    "device_type": "cisco_ios",     # See device type list below
    "host": "192.168.1.1",
    "username": "admin",
    "password": "secret",
    "secret": "enable_secret",      # Required for devices that need enable mode
    "port": 22,                     # Default SSH port
    "timeout": 30,                  # Connection timeout in seconds
    "session_log": "session.log",   # Optional: log all CLI I/O to a file
}

with ConnectHandler(**device) as conn:
    output = conn.send_command("show version")
    print(output)
# Connection auto-closes on context manager exit

Device Types Reference

python
# Common device_type values:
# cisco_ios        — Cisco IOS / IOS-XE
# cisco_nxos       — Cisco NX-OS (Nexus)
# cisco_xr         — Cisco IOS-XR
# cisco_asa        — Cisco ASA
# juniper_junos    — Juniper JunOS
# arista_eos       — Arista EOS
# linux            — Linux hosts (servers, Raspberry Pi, etc.)
# paloalto_panos   — Palo Alto PAN-OS
# fortinet         — Fortinet FortiOS
# mikrotik_routeros — MikroTik RouterOS

# For SSH key authentication instead of password:
device = {
    "device_type": "cisco_ios",
    "host": "192.168.1.1",
    "username": "admin",
    "use_keys": True,
    "key_file": "/home/user/.ssh/id_rsa",
}

Enable Mode

python
# Option 1: Auto-enter enable at connection time (recommended)
device = {
    "device_type": "cisco_ios",
    "host": "192.168.1.1",
    "username": "admin",
    "password": "secret",
    "secret": "enable_secret",
}
with ConnectHandler(**device) as conn:
    conn.enable()                    # Enter privileged exec
    output = conn.send_command("show running-config")

# Option 2: Check and enter enable as needed
with ConnectHandler(**device) as conn:
    if conn.check_enable_mode():
        print("Already in enable mode")
    else:
        conn.enable()

Sending Configuration

python
from netmiko import ConnectHandler

commands = [
    "interface GigabitEthernet0/1",
    "description AUTOMATION-TEST",
    "no shutdown",
]

with ConnectHandler(**device) as conn:
    conn.enable()
    # send_config_set handles 'configure terminal' and 'end' automatically
    output = conn.send_config_set(commands)
    print(output)

    # Save the config after changes
    conn.save_config()    # Runs 'write memory' or 'copy run start' as appropriate

Batch Operations Across Multiple Devices

python
from netmiko import ConnectHandler
from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any

DEVICES = [
    {"host": "10.0.0.1", "device_type": "cisco_ios"},
    {"host": "10.0.0.2", "device_type": "cisco_ios"},
    {"host": "10.0.0.3", "device_type": "arista_eos"},
]
BASE_CREDS = {"username": "admin", "password": "secret"}

def run_command_on_device(device_params: dict, command: str) -> dict[str, Any]:
    params = {**device_params, **BASE_CREDS}
    host = params["host"]
    try:
        with ConnectHandler(**params) as conn:
            output = conn.send_command(command)
        return {"host": host, "output": output, "error": None}
    except NetmikoAuthenticationException:
        return {"host": host, "output": None, "error": "Authentication failed"}
    except NetmikoTimeoutException:
        return {"host": host, "output": None, "error": "Connection timed out"}
    except Exception as e:
        return {"host": host, "output": None, "error": str(e)}

# Run in parallel (max 10 concurrent connections)
results = []
with ThreadPoolExecutor(max_workers=10) as executor:
    futures = {
        executor.submit(run_command_on_device, d, "show version"): d["host"]
        for d in DEVICES
    }
    for future in as_completed(futures):
        results.append(future.result())

for r in results:
    if r["error"]:
        print(f"{r['host']}: ERROR — {r['error']}")
    else:
        print(f"{r['host']}: OK")

Parsing Output

python
from netmiko import ConnectHandler
import re

# TextFSM parsing (returns structured list of dicts when templates exist)
with ConnectHandler(**device) as conn:
    # use_textfsm=True applies NTC-templates automatically for known commands
    parsed = conn.send_command("show ip interface brief", use_textfsm=True)
    # Returns list of dicts: [{"intf": "Gi0/0", "ipaddr": "10.0.0.1", ...}]
    for intf in parsed:
        print(f"{intf['intf']}: {intf['ipaddr']} — {intf['status']}/{intf['proto']}")

# Manual regex parsing when TextFSM templates don't exist
BGP_NEIGHBOR_RE = re.compile(
    r"^(?P<ip>\d{1,3}(?:\.\d{1,3}){3})\s+\d+\s+(?P<as>\d+)"
    r"\s+\d+\s+\d+\s+\d+\s+\d+\s+(?P<uptime>\S+)\s+(?P<state>\S+)",
    re.MULTILINE,
)

with ConnectHandler(**device) as conn:
    raw = conn.send_command("show bgp summary")

for m in BGP_NEIGHBOR_RE.finditer(raw):
    print(f"Neighbor {m.group('ip')} (AS {m.group('as')}): {m.group('state')}")

Error Handling Patterns

python
from netmiko import ConnectHandler
from netmiko.exceptions import (
    NetmikoAuthenticationException,
    NetmikoTimeoutException,
    NetMikoTimeoutException,  # Legacy alias — handle both
)
import socket

def safe_connect(device_params: dict) -> dict:
    host = device_params.get("host", "unknown")
    try:
        conn = ConnectHandler(**device_params)
        return {"conn": conn, "error": None}
    except NetmikoAuthenticationException:
        return {"conn": None, "error": f"{host}: authentication failed"}
    except (NetmikoTimeoutException, NetMikoTimeoutException):
        return {"conn": None, "error": f"{host}: SSH timeout"}
    except socket.gaierror:
        return {"conn": None, "error": f"{host}: DNS resolution failed"}
    except ConnectionRefusedError:
        return {"conn": None, "error": f"{host}: SSH port not open"}
    except Exception as e:
        return {"conn": None, "error": f"{host}: {type(e).__name__}: {e}"}

Anti-Patterns

python
# BAD: Not using context manager — connection leaks if an exception occurs
conn = ConnectHandler(**device)
output = conn.send_command("show version")
# If exception happens here, conn.disconnect() is never called
conn.disconnect()

# GOOD: Always use context manager
with ConnectHandler(**device) as conn:
    output = conn.send_command("show version")

# BAD: Hardcoding credentials in source code
device = {
    "host": "10.0.0.1",
    "username": "admin",
    "password": "MyPassword123",   # Never do this
}

# GOOD: Load from environment variables or a secrets manager
import os
device = {
    "host": "10.0.0.1",
    "username": os.environ["NET_USERNAME"],
    "password": os.environ["NET_PASSWORD"],
}

# BAD: Running batch operations sequentially — very slow at scale
for d in devices:
    result = run_command_on_device(d, "show version")  # Sequential, slow

# GOOD: Use ThreadPoolExecutor for parallel SSH connections (see Batch Operations above)

# BAD: Sending config without saving
conn.send_config_set(["interface Gi0/1", "description CHANGED"])
# Config is in running-config only — lost on reload

# GOOD: Always save after config changes
conn.send_config_set(["interface Gi0/1", "description CHANGED"])
conn.save_config()

Best Practices

  • Always use context managers (with ConnectHandler(...) as conn) for automatic cleanup
  • Store credentials in environment variables or a vault — never in source code
  • Set explicit timeout values — default can be too long for large-scale automation
  • Use session_log during development to capture full CLI I/O for debugging
  • Use use_textfsm=True on supported commands for structured output — much easier to process
  • Wrap all connections in try/except to handle unreachable devices gracefully in batch jobs
  • Limit parallel threads to 10–20 — more can exhaust SSH sessions on older devices

Related Skills

  • cisco-ios-patterns
  • network-bgp-diagnostics
  • network-config-validation

常见问题

Netmiko Ssh Automation AI 技能有什么作用?

Multi-vendor network device SSH automation using Python Netmiko — connecting, sending commands, parsing output, handling enable mode, error handling, and batch operations across device lists.

为什么在 TypingMind 中使用 Netmiko Ssh Automation?

因为您只需安装一次,就能搭配任何模型使用。Netmiko Ssh Automation 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Netmiko Ssh Automation?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/arsallls/claude-network-skills/tree/main/skills/netmiko-ssh-automation。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Netmiko Ssh Automation?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Netmiko Ssh Automation 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Netmiko Ssh Automation 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Netmiko Ssh Automation AI 技能免费吗?

是的。arsallls 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇