Network Automation- Day 2

To find unused ports on a Cisco switch using python

To find unused ports on a Cisco switch, you can use the netmiko library in Python, which is a library used to connect to network devices. Here's a basic script to find unused ports on a Cisco switch:

  1. First, you need to install the required library:

    pip install netmiko

    1. Use the following Python script:
    from netmiko import ConnectHandler
    from datetime import datetime

    def find_unused_ports(device):
        connection = ConnectHandler(**device)
        output = connection.send_command('show interfaces | include line protocol')
        connection.disconnect()

        unused_ports = []

        for line in output.split("\n"):
            if "down, line protocol is down" in line:
                port = line.split()[0]
                unused_ports.append(port)

        return unused_ports

    if __name__ == "__main__":
        device = {
            'device_type': 'cisco_ios',
            'ip': 'YOUR_SWITCH_IP',
            'username': 'YOUR_USERNAME',
            'password': 'YOUR_PASSWORD',
            'secret': 'YOUR_SECRET',  # Optional, if you have an enable password
        }

        start_time = datetime.now()

        unused_ports_list = find_unused_ports(device)

        if unused_ports_list:
            print("Unused Ports:")
            for port in unused_ports_list:
                print(port)
        else:
            print("No unused ports found.")

        end_time = datetime.now()
        print(f"\nScript execution time: {end_time - start_time}")

Replace YOUR_SWITCH_IP, YOUR_USERNAME, YOUR_PASSWORD, and YOUR_SECRET with your switch's credentials.

This script connects to the switch, runs the show interfaces command, and looks for interfaces that are both administratively down and operationally down. It then prints out the list of unused ports.

Here is the breakdown of above script

  1. Importing Necessary Libraries:
from netmiko import ConnectHandler
from datetime import datetime
  • netmiko is a Python library that simplifies the process of connecting to network devices.

  • ConnectHandler is a function within netmiko that establishes the connection.

  • datetime is imported to measure the script's execution time.

  1. Function to Find Unused Ports:
def find_unused_ports(device):
    connection = ConnectHandler(**device)
    output = connection.send_command('show interfaces | include line protocol')
    connection.disconnect()

    unused_ports = []

    for line in output.split("\n"):
        if "down, line protocol is down" in line:
            port = line.split()[0]
            unused_ports.append(port)

    return unused_ports
  • The function find_unused_ports takes a device dictionary as an argument which contains the device's connection details.

  • ConnectHandler(**device) establishes a connection to the device using the details provided.

  • The command show interfaces | include line protocol is sent to the device. This command displays the status of all interfaces, but only lines containing "line protocol" are shown.

  • The function then checks each line for the status "down, line protocol is down". If this status is found, it means the port is unused.

  • The port name is extracted and added to the unused_ports list.

  • The function returns the list of unused ports.

  1. Main Execution:
if __name__ == "__main__":
    device = {
        'device_type': 'cisco_ios',
        'ip': 'YOUR_SWITCH_IP',
        'username': 'YOUR_USERNAME',
        'password': 'YOUR_PASSWORD',
        'secret': 'YOUR_SECRET',  # Optional, if you have an enable password
    }

    start_time = datetime.now()

    unused_ports_list = find_unused_ports(device)

    if unused_ports_list:
        print("Unused Ports:")
        for port in unused_ports_list:
            print(port)
    else:
        print("No unused ports found.")

    end_time = datetime.now()
    print(f"\nScript execution time: {end_time - start_time}")
  • The if __name__ == "__main__": line ensures that the code below it is only executed if the script is run directly (not imported as a module).

  • The device dictionary contains the connection details for the Cisco switch. You need to replace placeholders like YOUR_SWITCH_IP with actual values.

  • The script measures the start time, calls the find_unused_ports function, and then measures the end time to calculate the total execution time.

  • The script prints out the unused ports or a message indicating no unused ports were found.