brunch

You can make anything
by writing

C.S.Lewis

파이썬 네트워크 프로그래밍 (#11 : netmiko)

파이썬 네트워크 자동화

"netmiko"를 이용한 파이썬 네트워크 자동화

단순히 원하는 설정을 입력하는 것이 아닌, 현재 설정 내용 및 상태를 확인 후에 그에 따른 조치를 취할 수 있는 간단한 스크립트입니다. 목표는 먼저 네트워크 장비에 port scan을 진행하고, 포트 중에 telnet port가 열려 있으면, 해당 설정을 삭제하는 스크립트입니다.  

스크립트는 아래와 같습니다.



import socket

from netmiko import ConnectHandler


# defined by service vendor and type

ios_router   = ["192.168.37.201", "192.168.37.202","192.168.37.203"]

ios_switch  = ["192.168.37.102","192.168.37.112"]

eos_router  = ["192.168.37.101", "192.168.37.111","192.168.37.204"]


def port_scan_delete_telnet_ios(target):

    for ip in target:

        for port in range(22,24):

            destination = (ip, port)

            try: 

                with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:

                    sock.settimeout(3)

                    connection = sock.connect(destination)

                    print(f" Target : {ip} / Open  port : {port}")

                    port_number = f"{port}"

                    if port_number == "23":

                        iso = {'device_type':'cisco_ios','ip':ip,'username':'devnet','password':'dn1001',}

                        net_connect = ConnectHandler(**iso)

                        commands = ['line vty 0 15','transport input ssh','no transport input all','no transport input telnet']

                        net_connect.send_config_set(commands)

                        print(f" * Removed telnet access service : {ip} ")

                        net_connect.disconnect()

            except:

                print(f" Target : {ip} / Close  port : {port}")  


def port_scan_delete_telnet_eos(target):

    for ip in target:

        for port in range(22,24):

            destination = (ip, port)

            try: 

                with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:

                    sock.settimeout(3)

                    connection = sock.connect(destination)

                    print(f" Target : {ip} / Open  port : {port}")

                    port_number = f"{port}"

                    if port_number == "23":

                        eos = {'device_type':'arista_eos','ip':ip,'username':'devnet','password':'dn1001'}

                        net_connect = ConnectHandler(**eos)

                        commands = ['no management telnet']

                        net_connect.enable()

                        net_connect.config_mode()

                        net_connect.send_config_set(commands,exit_config_mode=False)

                        print(f" * Removed telnet access service : {ip} ")

                        net_connect.disconnect()

            except:

                print(f" Target : {ip} / Close  port : {port}")  


print("=" * 100)

print("* Cisco Router Enterprise Network Port Scan")

port_scan_delete_telnet_ios(ios_router)

print("-" * 100)


print("* Cisco Switch Enterprise Network Port Scan")

port_scan_delete_telnet_ios(ios_switch)

print("-" * 100)


print("* Arista Enterprise Network Port Scan")

port_scan_delete_telnet_eos(eos_router)

print("-" * 100)



장비 별 사용할 함수를 만들고, socket을 이용하여 port scan을 진행합니다. 이후 검색 중에 port 23이 열린 것을 확인하면 해당 장비에 접속하여 telnet 서비스를 제거합니다. 접속은 netmiko로 진행되며, 모든 장비에 접속을 하는 것이 아닌 이슈가 되는 장비에만 접속하여 해당 설정을 집어넣습니다.

아래는 해당 스크립트에 대한 결과입니다. 

실행 결과 (1)

첫 번째 스크립트 실행에서 23 포트가 열려 있는 201, 202, 203, 102, 112 장비를 발견하고 telnet 서비스를 제외했습니다.


실행 결과 (2)

두 번째 실행결과에서는 모든 telnet port가 이미 close 되어 있기 때문에 추가적인 작업은 발생하지 않고 단순 port scan 작업만 진행되었습니다. 



마무리

netmiko + socket을 이용하여 실무에서도 적용 가능한 스크립트를 만들어 봤습니다. 해당 내용을 실무 환경에 수정 보완을 한다면 좀 더 멋진 스크립트가 될 수 있을 것 같습니다. 저도 나중에 좀 더 나은 스크립트를 만들게 되면 공유하도록 하겠습니다.

매거진의 이전글 파이썬 네트워크 프로그래밍 (#10:netmiko)

작품 선택

키워드 선택 0 / 3 0

댓글여부

afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari