본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)280k · #363

netmiko-ssh-automation

하는 일

이 도구는 Python을 사용해 라우터나 스위치 같은 네트워크 장비의 작업을 자동화하도록 돕습니다. 안전하게 정보를 수집하거나, 통제된 설정 변경을 할 수 있습니다.

사용하는 경우

  • ✓여러 장비에서 'show' 명령으로 정보를 수집할 때.
  • ✓네트워크 설정을 확인하는 간단한 스크립트를 만들 때.
  • ✓네트워크 스크립트에 안전 장치와 오류 처리를 추가할 때.

스킬 링크

https://github.com/affaan-m/ECC/blob/main/skills/netmiko-ssh-automation/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/skills/netmiko-ssh-automation/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“모든 라우터에서 네트워크 인터페이스 상태를 수집해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

코드는 안전한 프로토콜(SSH)로 네트워크 장비에 연결하고, 명령을 실행하며, 응답을 처리할 수 있습니다. 문제를 막기 위한 안전 조치가 포함되어 있습니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Netmiko SSH Automation

Use this skill when writing or reviewing Python automation that connects to network devices with Netmiko. Keep the default path read-only; config changes need a separate change window, peer review, and rollback plan.

When to Use

  • Collecting show command output across routers, switches, or firewalls.
  • Building a small audit script for interface, routing, or config evidence.
  • Adding timeouts and exception handling to network SSH scripts.
  • Parsing command output with TextFSM when a template exists.
  • Reviewing automation before it touches production devices.

Safety Defaults

  • Start with read-only send_command() collection.
  • Keep inventory small and explicit; do not sweep whole address ranges.
  • Use environment variables, a vault, or getpass; never hardcode credentials.
  • Set connection and read timeouts.
  • Limit concurrency so older devices are not overloaded.
  • Require an explicit operator flag before send_config_set().
  • Do not call save_config() until the change has been verified and approved.

Read-Only Connection Pattern

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("Authentication failed")
except NetmikoTimeoutException:
    print("SSH connection timed out")
except ReadTimeout:
    print("Command read timed out")

Use placeholder addresses from documentation ranges in examples. Keep real inventory in an ignored local file or a secrets-managed system.

Batch Collection

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

Keep max_workers low unless the device estate and AAA systems are known to handle higher connection volume.

Structured Parsing

Netmiko can ask TextFSM, TTP, or Genie to parse supported command output. Treat parser output as an optimization, not the only evidence path.

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("No parser template matched; store raw output for review")
else:
    for row in parsed:
        print(row)

If parsing drives a blocking decision, keep the raw command output alongside the parsed result so an operator can inspect mismatches.

Guarded Config Pattern

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("Dry run only. Candidate commands:")
    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)

…
자주 묻는 질문

도구는 비밀번호를 어떻게 다루나요?

환경 변수를 쓰거나 비밀번호를 입력받는 등 안전한 방법을 사용하며, 스크립트에 직접 적어 넣지 않습니다.

위험한 설정 변경도 할 수 있나요?

가능하지만 매우 신중해야 합니다. 설정 변경에는 추가 확인과 검토 단계가 필요해서 안전을 보장합니다.

연결이 실패하면 어떻게 되나요?

도구는 연결이나 명령 실패를 처리하도록 설계되어 있으며, 전체 과정을 멈추지 않고 오류를 알려 줍니다.

상세 정보

작성자의 원본 설명

Safe Python Netmiko patterns for read-only collection, bounded batch SSH, TextFSM parsing, guarded config changes, timeouts, and network automation error handling. Use when automating network device access with Python Netmiko, whether collecting state or pushing guarded config changes.

repo: affaan-m/ECC

인기도

GitHub 스타
280k
순위
#363
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬