Let’s dive into setting up a Cisco switch using Python automation! This is a great way to streamline network configuration tasks, and I’ll walk you through the process step-by-step. We’ll assume you’re working with a Cisco IOS-based switch, and I’ll use Python with libraries like paramiko or netmiko to handle the automation. These are popular choices for SSH-based network device management.
What You’ll Need
- A Cisco Switch: Accessible via SSH (IP address, username, password).
- Python Installed: Version 3.x recommended.
- Libraries: Install netmiko (a higher-level abstraction over SSH) with pip install netmiko.
- Basic Switch Info: IP address, credentials, and the configuration you want to apply.
Step 1: Basic Connection
Let’s start with a simple script to connect to the switch and run a command (e.g., show version). Here’s an example using netmiko:
python
from netmiko import ConnectHandler
# Define the device details
switch = {
    'device_type': 'cisco_ios',
    'host': '192.168.1.10',  # Replace with your switch IP
    'username': 'admin',     # Replace with your username
    'password': 'cisco123',  # Replace with your password
}
# Establish SSH connection
try:
    connection = ConnectHandler(**switch)
    print("Connected successfully!")
    # Run a command
    output = connection.send_command("show version")
    print(output)
    # Disconnect
    connection.disconnect()
except Exception as e:
    print(f"Failed to connect: {e}")Run this script to test connectivity. If it works, you’ll see the switch’s version info. Adjust the IP, username, and password to match your setup.
Step 2: Configuring the Switch
Now, let’s automate some basic configurations—like setting a hostname, creating a VLAN, and configuring an interface. We’ll use send_config_set() to send multiple commands:
python
from netmiko import ConnectHandler
switch = {
    'device_type': 'cisco_ios',
    'host': '192.168.1.10',
    'username': 'admin',
    'password': 'cisco123',
}
# Configuration commands
config_commands = [
    'hostname MySwitch',
    'vlan 10',
    'name Sales',
    'exit',
    'interface gigabitEthernet0/1',
    'switchport mode access',
    'switchport access vlan 10',
    'description Connected_to_Sales',
    'no shutdown'
]
try:
    connection = ConnectHandler(**switch)
    print("Connected successfully!")
    # Send configuration commands
    output = connection.send_config_set(config_commands)
    print("Configuration applied:")
    print(output)
    # Save the configuration
    connection.save_config()
    print("Configuration saved!")
    connection.disconnect()
except Exception as e:
    print(f"Error: {e}")This script sets the hostname to “MySwitch”, creates VLAN 10 named “Sales”, and configures interface Gi0/1 as an access port in VLAN 10. The save_config() ensures changes persist after a reboot.
Step 3: Scaling It Up
For multiple switches or more complex configs, you can:
- Use a List of Devices: Store device details in a list or JSON file and loop through them.
- Template Configs: Use Jinja2 to generate commands dynamically.
- Error Handling: Add checks (e.g., verify VLAN creation with show vlan brief).
Here’s an example with multiple switches:
python
from netmiko import ConnectHandler
devices = [
    {'host': '192.168.1.10', 'username': 'admin', 'password': 'cisco123'},
    {'host': '192.168.1.11', 'username': 'admin', 'password': 'cisco123'}
]
config_commands = [
    'hostname Switch_{}',
    'vlan 20',
    'name Engineering',
    'exit'
]
for i, device in enumerate(devices, 1):
    device['device_type'] = 'cisco_ios'
    try:
        connection = ConnectHandler(**device)
        print(f"Connected to {device['host']}")
        
        # Customize hostname per switch
        commands = [cmd.format(i) if '{}' in cmd else cmd for cmd in config_commands]
        connection.send_config_set(commands)
        connection.save_config()
        
        print(f"Configured Switch_{i}")
        connection.disconnect()
    except Exception as e:
        print(f"Failed on {device['host']}: {e}")Tips
- Enable SSH: On the switch, ensure SSH is enabled (crypto key generate rsa, ip ssh version 2, etc.).
- Timeouts: For slow devices, adjust netmiko timeouts (e.g., global_delay_factor=2 in the device dict).
- Debugging: Use connection.send_command(“show run”) to verify changes.
- Security: Store credentials securely (e.g., environment variables or a config file).
What’s your setup like? Want to tweak this for a specific switch model or configuration? Let me know!
