Netmiko - Python SSH 라이브러리

22 조회 2025-11-17 오픈소스 도구
GitHub 문서

Netmiko - 네트워크 자동화를 위한 Python 라이브러리

개요

Netmiko는 Kirk Byers가 개발한 Python SSH 라이브러리로, Paramiko를 기반으로 네트워크 장비 관리에 특화되어 있습니다.

주요 기능

1. 간단한 연결 및 명령 실행

from netmiko import ConnectHandler

device = {
    'device_type': 'cisco_ios',
    'host': '192.168.1.1',
    'username': 'admin',
    'password': 'password',
}

with ConnectHandler(**device) as net_connect:
    output = net_connect.send_command('show ip interface brief')
    print(output)

2. 설정 변경

config_commands = [
    'interface GigabitEthernet0/1',
    'description Link to Core',
    'no shutdown'
]

output = net_connect.send_config_set(config_commands)
net_connect.save_config()

3. 지원 플랫폼 (200+)

Cisco

  • cisco_ios
  • cisco_nxos
  • cisco_xr
  • cisco_asa
  • cisco_wlc

Juniper

  • juniper_junos

Arista

  • arista_eos

HP/HPE

  • hp_comware
  • hp_procurve

Dell

  • dell_force10
  • dell_os10

Fortinet

  • fortinet

Palo Alto

  • paloalto_panos

고급 기능

1. 병렬 처리

from concurrent.futures import ThreadPoolExecutor
from netmiko import ConnectHandler

devices = [
    {'device_type': 'cisco_ios', 'host': '192.168.1.1', ...},
    {'device_type': 'cisco_ios', 'host': '192.168.1.2', ...},
    # 100+ devices
]

def backup_device(device):
    with ConnectHandler(**device) as conn:
        output = conn.send_command('show running-config')
        filename = f"{device['host']}_config.txt"
        with open(filename, 'w') as f:
            f.write(output)
        return filename

with ThreadPoolExecutor(max_workers=20) as executor:
    results = list(executor.map(backup_device, devices))

2. 파일 전송 (SCP)

device = ConnectHandler(**device_info)
transfer_dict = {
    'source_file': 'local_file.txt',
    'dest_file': 'remote_file.txt',
    'file_system': 'flash:'
}
transfer = device.transfer_file(transfer_dict)

3. 프롬프트 자동 감지

# 자동으로 enable 모드로 진입
device = {
    'device_type': 'cisco_ios',
    'host': '192.168.1.1',
    'username': 'admin',
    'password': 'password',
    'secret': 'enable_password',  # enable password
}

with ConnectHandler(**device) as net_connect:
    # 자동으로 enable 모드로 전환됨
    output = net_connect.send_command('show run')

4. 텍스트FSM 통합

# 구조화된 데이터 파싱
output = net_connect.send_command(
    'show ip interface brief',
    use_textfsm=True
)

# 결과가 딕셔너리 리스트로 반환됨
for interface in output:
    print(f"Interface: {interface['intf']}, IP: {interface['ipaddr']}")

에러 처리

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

try:
    device = ConnectHandler(**device_info)
except NetmikoTimeoutException:
    print("Device not reachable")
except NetmikoAuthenticationException:
    print("Authentication failed")
except Exception as e:
    print(f"Unknown error: {e}")

성능 최적화 팁

1. 빠른 CLI 모드

device = ConnectHandler(**device_info)
device.fast_cli = True  # 더 빠른 명령 실행

2. 글로벌 딜레이 설정

device = ConnectHandler(
    **device_info,
    global_delay_factor=2  # 느린 장비에 대응
)

3. 세션 로깅

device = ConnectHandler(
    **device_info,
    session_log='session.log'
)

실전 예제: 대량 장비 설정 변경

import csv
from netmiko import ConnectHandler
from datetime import datetime

def update_devices_from_csv(csv_file):
    results = []

    with open(csv_file, 'r') as f:
        reader = csv.DictReader(f)
        devices = list(reader)

    for device_data in devices:
        device = {
            'device_type': 'cisco_ios',
            'host': device_data['ip'],
            'username': 'admin',
            'password': 'password',
        }

        try:
            with ConnectHandler(**device) as conn:
                # 백업
                backup = conn.send_command('show running-config')
                backup_file = f"backup_{device['host']}_{datetime.now().strftime('%Y%m%d')}.txt"
                with open(backup_file, 'w') as f:
                    f.write(backup)

                # 설정 변경
                commands = [
                    f"interface {device_data['interface']}",
                    f"description {device_data['description']}",
                ]
                output = conn.send_config_set(commands)
                conn.save_config()

                results.append({
                    'host': device['host'],
                    'status': 'Success',
                    'backup': backup_file
                })
        except Exception as e:
            results.append({
                'host': device['host'],
                'status': f'Failed: {e}'
            })

    return results

# 사용
results = update_devices_from_csv('devices.csv')
for r in results:
    print(f"{r['host']}: {r['status']}")

설치

pip install netmiko

장점

✓ 간단하고 직관적인 API ✓ 200+ 장비 플랫폼 지원 ✓ 활발한 커뮤니티 ✓ Ansible과 통합 가능 ✓ 빠른 프로토타이핑

단점

✗ SSH 기반으로 속도 제한 ✗ 대규모 환경에서는 병렬 처리 필요 ✗ API 기반 장비에는 부적합

라이센스

MIT

링크

  • GitHub: https://github.com/ktbyers/netmiko
  • 문서: https://ktbyers.github.io/netmiko/
  • PyPI: https://pypi.org/project/netmiko/