느리지만 단단한 IT 인프라 이야기

Coding/Python

[Python] Nemiko를 통한 Axgate 자동 로그인 & 다중 명령어 전송

바둑이 아저씨 2026. 2. 19. 22:02

python netmiko ( 출처 : moisio.fr )

이번에는 실제로 자주 사용하는 설정 변경 명령어를 commands.txt에 넣고 자동으로 적용하는 예시를 보여드리겠습니다.

예를 들어, 인터페이스에 secondary IP를 추가하거나 VLAN 설정, NAT 룰 추가 등 반복적인 설정 작업을 파일 하나로 처리할 수 있습니다.


사용 환경 및 준비물

  • Python 3.8 이상
  • pip install netmiko
  • AXGATE SSH 포트 (기본 2222번 등)
  • commands.txt 파일 – 설정 모드 진입부터 write까지 순서대로 작성
  • session_log = 'axgate_log.txt' → 설정 실패 시 반드시 확인

commands.txt 예시 (실제 설정 적용용)

# AXGATE 인터페이스 secondary IP 추가 예시
# 빈 줄과 #으로 시작하는 주석은 무시됩니다

conf terminal
interface eth1
ip address 10.10.10.1/24 secondary
end
write

→ conf t → 인터페이스 진입 → 설정 → end → write 순서로 정확히 작성하세요.


전체 코드 예시 (설정 적용 버전)

import time
import os
from netmiko import ConnectHandler

axgate_device = {
    'device_type': 'generic_termserver',
    'host': '192.168.100.1',
    'username': 'axadmin',
    'password': 'Admin12#$',
    'port': 2222,
    'session_log': 'axgate_setting_log.txt',  # 설정용 로그 파일명 변경 추천
    # 'global_cmd_verify': False,  # 필요 시 추가 (출력 검증 비활성화)
}

net_connect = None

COMMAND_FILE = 'commands.txt'

try:
    if not os.path.exists(COMMAND_FILE):
        print(f"오류: {COMMAND_FILE} 파일이 없습니다.")
        exit()

    print(f"Connecting to {axgate_device['host']}... port {axgate_device['port']}")
    net_connect = ConnectHandler(**axgate_device)
    time.sleep(2.5)

    print("Step 1: Username 전송...")
    net_connect.write_channel(axgate_device['username'] + "\n")
    time.sleep(1.2)

    print("Step 2: Password 전송...")
    net_connect.write_channel(axgate_device['password'] + "\n")
    time.sleep(2.5)

    output = net_connect.read_channel()
    print(f"--- 로그인 후 출력 ---\n{output}\n-------------------")

    if "#" in output or ">" in output:
        print("로그인 성공! commands.txt 설정 명령어를 순차 적용합니다...")

        with open(COMMAND_FILE, 'r', encoding='utf-8') as f:
            commands = [line.strip() for line in f if line.strip() and not line.strip().startswith('#')]

        for cmd in commands:
            print(f"\n실행 중: {cmd}")
            # 설정 명령어는 응답이 길거나 프롬프트가 늦게 나올 수 있으므로 여유롭게
            res = net_connect.send_command_timing(
                cmd,
                last_read=4.0,          # 설정 명령은 4~6초 여유 추천
                strip_prompt=False,     # 프롬프트 유지 (디버깅 용이)
                strip_command=False
            )
            print(f"결과:\n{res}\n{'-'*60}")
            time.sleep(0.8)  # 명령어 간 약간의 간격 → 장비 부하 방지

        print("\n모든 설정 명령어 적용 완료!")

    else:
        print("로그인 실패 → axgate_setting_log.txt 파일 확인하세요.")

except Exception as e:
    print(f"오류 발생: {e}")

finally:
    if net_connect:
        net_connect.disconnect()
        print("세션 종료.")

주요 포인트 & 설정 시 주의사항

  1. 명령어 순서 엄격 준수
    conf terminal → 설정 → end → write 순서를 반드시 지켜야 합니다.
  2. last_read 시간 늘리기
    설정 명령어는 출력이 많아 3.0초로는 부족할 수 있으니 4.0~6.0초 추천
  3. time.sleep(0.8) 추가
    명령어 간격을 두어 장비가 숨을 쉴 수 있게 해줍니다.
  4. 로그 파일명 구분
    점검용/설정용 로그 파일명을 다르게 하면 추적 편리 (예: axgate_setting_log.txt)
  5. 설정 전/후 확인 명령 추가 추천
    commands.txt 맨 위에 show ip int brief, 맨 아래에 다시 show ip int brief 넣으면 변경 전후 비교 가능

※ 설정 명령 자동화는 매우 위험할 수 있습니다.
반드시 테스트 환경에서 먼저 검증하고, 백업( show running-config 저장 등)을 확보한 후 사용하세요!


이 방법으로 수십 대 장비에 동일한 secondary IP나 VLAN 설정을 한 번에 적용할 수 있습니다.

궁금한 점이 더 있으시다면 댓글로 부탁드립니다.
감사합니다.