Communitygithub.com

netmiko-ssh-automation

Python Netmiko を使用したネットワーク自動化のための安全なパターン:読み取り専用収集、制限付きバッチSSH、TextFSMパーシング、ガード付き設定変更、タイムアウト、エラーハンドリング。Python Netmiko を使用したネットワーク機器アクセス(状態収集やガード付き設定変更のプッシュ)を自動化する際に使用します。

netmiko-ssh-automation とは?

このスキルは、Python の Netmiko ライブラリを使用してネットワーク機器(ルーター、スイッチ、ファイアウォールなど)への SSH 自動化を記述・レビューする際のベストプラクティスを提供します。読み取り専用の状態収集をデフォルトとし、設定変更は明示的なフラグを必要とするガード付きパターンを採用することで、本番環境への影響を最小限に抑えます。 主な機能として、`send_command()` による安全な読み取り専用接続、`ThreadPoolExecutor` を使った制限付きバッチ収集、TextFSM/Genie による構造化パーシング、そして設定変更時のドライラン機構と変更前後のエビデンス取得が含まれます。タイムアウト設定(`conn_timeout`、`auth_timeout`、`read_timeout_override`)や例外処理(`NetmikoAuthenticationException` など)も標準化されています。 このスキルは、構成監査スクリプトの作成、show コマンド出力の一括収集、ネットワーク設定変更の自動化(変更承認プロセスと組み合わせて)、および既存の自動化コードのレビューに適しています。反パターンとして、パスワードのハードコーディング、無制限のスキャン、設定変更のデフォルト実行などを明確に禁止しています。 対応プラットフォームは、Netmiko がサポートするすべてのネットワークベンダー(Cisco、Juniper、Arista、 Palo Alto など)です。TextFSM テンプレートが利用可能な場合、構造化データの抽出も可能です。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/netmiko-ssh-automation

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Netmiko SSH 自動化

このスキルは、Netmiko を使用してネットワーク機器に接続する Python 自動化コードを記述またはレビューする際に使用します。デフォルトのパスは読み取り専用に保ちます。設定変更には、別途変更ウィンドウ、ピアレビュー、ロールバック計画が必要です。

使用するタイミング

  • ルーター、スイッチ、ファイアウォールから show コマンド出力を収集する場合。
  • インターフェース、ルーティング、設定のエビデンスを取得するための小規模な監査スクリプトを構築する場合。
  • ネットワーク SSH スクリプトにタイムアウトと例外処理を追加する場合。
  • TextFSM テンプレートが存在する場合に、コマンド出力をパースする場合。
  • 本番デバイスに影響を与える前に自動化コードをレビューする場合。

安全上のデフォルト

  • 最初は読み取り専用の send_command() 収集から始めます。
  • インベントリは小さく、明示的に指定します。アドレス範囲全体をスキャンしないでください。
  • 環境変数、ボールト、または getpass を使用します。認証情報をハードコードしないでください。
  • 接続タイムアウトと読み取りタイムアウトを設定します。
  • 同時実行数を制限して、古いデバイスに過負荷がかからないようにします。
  • send_config_set() の前に明示的なオペレーターフラグを要求します。
  • 変更が確認および承認されるまで save_config() を呼び出さないでください。

読み取り専用接続パターン

import os
from getpass import getpass
from netmiko import ConnectHandler
from netmiko.exceptions import (
    NetmikoAuthenticationException,
    NetmikoTimeoutException,
    ReadTimeout,
)

device = {
    "device_type": "cisco_ios",
    "host": "192.0.2.10",
    "username": os.environ.get("NETMIKO_USERNAME") or input("ユーザー名: "),
    "password": os.environ.get("NETMIKO_PASSWORD") or getpass("パスワード: "),
    "secret": os.environ.get("NETMIKO_ENABLE_SECRET"),
    "conn_timeout": 10,
    "auth_timeout": 20,
    "banner_timeout": 15,
    "read_timeout_override": 30,
}

try:
    with ConnectHandler(**device) as conn:
        if device.get("secret") and not conn.check_enable_mode():
            conn.enable()
        output = conn.send_command("show ip interface brief", read_timeout=30)
        print(output)
except NetmikoAuthenticationException:
    print("認証に失敗しました")
except NetmikoTimeoutException:
    print("SSH接続がタイムアウトしました")
except ReadTimeout:
    print("コマンド読み取りがタイムアウトしました")

例ではドキュメント用のアドレス範囲からプレースホルダーを使用してください。実際のインベントリは、無視リストに含まれるローカルファイルまたはシークレット管理システムに保存してください。

バッチ収集

from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any

def collect_show(device: dict[str, Any], command: str) -> dict[str, Any]:
    host = device["host"]
    try:
        with ConnectHandler(**device) as conn:
            output = conn.send_command(command, read_timeout=45)
        return {"host": host, "ok": True, "output": output}
    except (NetmikoAuthenticationException, NetmikoTimeoutException, ReadTimeout) as exc:
        return {"host": host, "ok": False, "error": type(exc).__name__}

results = []
with ThreadPoolExecutor(max_workers=8) as pool:
    futures = [pool.submit(collect_show, device, "show version") for device in devices]
    for future in as_completed(futures):
        results.append(future.result())

デバイスの環境とAAAシステムが高い接続ボリュームを処理できることが確認されていない限り、max_workers は低く保ってください。

構造化パーシング

Netmiko は、サポートされているコマンド出力をパースするために TextFSM、TTP、または Genie に要求できます。パーサーの出力は最適化として扱い、唯一のエビデンス経路としては扱わないでください。

with ConnectHandler(**device) as conn:
    parsed = conn.send_command(
        "show ip interface brief",
        use_textfsm=True,
        raise_parsing_error=False,
        read_timeout=30,
    )

if isinstance(parsed, str):
    print("パーサーテンプレートが一致しませんでした。レビューのために生の出力を保存してください")
else:
    for row in parsed:
        print(row)

パーシングがブロッキング判断を左右する場合は、パース結果と一緒に生のコマンド出力も保存しておくと、オペレーターが不一致を検査できます。

ガード付き設定パターン

import os

commands = [
    "interface GigabitEthernet0/1",
    "description CHANGE-1234 UPLINK-TO-CORE",
]

apply_changes = os.environ.get("APPLY_NETWORK_CHANGES") == "1"

if not apply_changes:
    print("ドライランのみ。候補コマンド:")
    print("\n".join(commands))
else:
    with ConnectHandler(**device) as conn:
        conn.enable()
        before = conn.send_command("show running-config interface GigabitEthernet0/1")
        output = conn.send_config_set(commands)
        after = conn.send_command("show running-config interface GigabitEthernet0/1")
        print(before)
        print(output)
        print(after)
        print("スタートアップコンフィグを保存する前に動作を確認してください。")

コンフィグの保存は別の承認ステップです。本番環境では、ロールバックスニペットを含め、変更記録に変更前後のエビデンスを取得してください。

レビューチェックリスト

  • スクリプトは明示的なインベントリソースを特定していますか?
  • 認証情報はソース、ログ、例外メッセージから除外されていますか?
  • conn_timeout、auth_timeout、コマンド read_timeout は設定されていますか?
  • 失敗はバッチ全体を停止することなく、デバイスごとに報告されていますか?
  • スクリプトは広範なスキャンや無制限の同時実行を避けていますか?
  • 設定変更はドライランまたは明示的なオペレーターフラグの背後にありますか?
  • save_config() は初期プッシュとは別で、検証と結びついていますか?

アンチパターン

  • パスワード、enable シークレット、または秘密鍵をソースにハードコーディングすること。
  • 設定変更コマンドをデフォルトのコードパスとして送信すること。
  • レビュー済みのインベントリではなく、CIDR 範囲に対して自動化を実行すること。
  • サニタイズなしで完全な running-config を共有システムにログ出力すること。
  • パーサーの成功を、デバイスの状態が正しいことの証明として扱うこと。

関連情報

  • スキル: cisco-ios-patterns
  • スキル: network-config-validation
  • スキル: network-interface-health

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

関連スキル