Profile picture

[Python] Cisco switch Port scan (Netmiko)

JaehyoJJAng2023년 12월 02일

개요

netmiko 라이브러리를 활용하여 시스코 스위치 장비에 port scan을 진행하고, telnet 포트가 열려있는 경우 해당 설정을 삭제하는 프로그램을 구현해보자.


코드

import socket
from netmiko import ConnectHandler

def port_scan_delete_telnet_ios(target: list[str]) -> None:
    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}")
                    if str(port) == "23":
                        iso = {"device_type": "cisco_ios_telnet", "ip": ip, "username": "sw1", "password": "sw1", "secret": "sw1"}
                        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 telent access service: {ip}")
                        net_connect.disconnect()
            except Exception as e:
                print(f"Target : {ip} / Close port : {port}")

def main() -> None:
    print("=" * 100)
    print("Cisco Switch Enterprise Network port scan")
    
    # 장비 IP 정의
    IOS_SWITCH :list[str] = ["192.168.219.130"]
    
    port_scan_delete_telnet_ios(target=IOS_SWITCH)
    
    print("=" * 100)

if __name__ == '__main__':
    main()

socket을 사용하여 port scan을 진행.


결과

image
23포트가 열려있는 장비를 발견 후 telent 서비스가 제외된 것을 볼 수 있다.


Loading script...