Communitygithub.com

netmiko-ssh-automation

Netmiko를 사용한 안전한 Python SSH 네트워크 자동화 패턴 - 읽기 전용 수집, 제한된 배치 SSH, TextFSM 파싱, 보호된 구성 변경, 타임아웃 및 오류 처리.

netmiko-ssh-automation란 무엇인가요?

이 스킬은 Netmiko 라이브러리를 사용하여 네트워크 장치에 대한 Python SSH 자동화를 작성하거나 검토할 때 참조하는 안전한 패턴 가이드입니다. 기본적으로 읽기 전용 `send_command()` 수집을 강조하며, 구성 변경은 별도의 변경 창, 동료 검토 및 롤백 계획을 요구합니다. TextFSM, TTP 또는 Genie를 통한 구조화된 출력 파싱을 지원하며, 파싱 결과를 최적화 도구로 사용할 것을 권장합니다. 대규모 장치 인벤토리를 스윕하지 않고 작고 명시적인 인벤토리로 제한된 동시성을 사용하며, 자격 증명을 소스 코드에 하드코딩하지 않고 환경 변수나 볼트를 사용합니다. 또한, 변경 승인을 위한 명시적 연산자 플래그, `save_config()`를 검증과 분리하는 원칙 등 네트워크 자동화의 주요 안티 패턴을 식별하고 안전한 자동화 실천법을 제공합니다.

지원 대상~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 Automation

이 스킬은 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("Username: "),
    "password": os.environ.get("NETMIKO_PASSWORD") or getpass("Password: "),
    "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("명령 읽기 시간 초과")

예제에서는 문서화된 테스트 범위의 플레이스홀더 주소를 사용하세요. 실제 인벤토리는 .gitignore에 추가된 로컬 파일이나 시크릿 관리 시스템에 보관하세요.

배치 수집

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())

max_workers는 장치 환경과 AAA 시스템이 더 높은 연결 볼륨을 처리할 수 있다는 것이 확인되지 않았다면 낮게 유지하세요.

구조화된 파싱

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 범위에 대해 자동화 실행.
  • 전체 실행 구성을 삭제하지 않고 공유 시스템에 로깅.
  • 파서 성공을 장치 상태가 올바르다는 증거로 취급.

참고

  • 스킬: 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.

관련 스킬