Automation of network devices, such as Cisco routers and switches, can be easily achieved using Python with the Netmiko library, designed to easily handle SSH connections. Next, I show you two basic scripts to view the configuration of a Cisco device and to automate the creation and configuration of VLANs.
1. Script to view the configuration of a Cisco device (router):
from netmiko import ConnectHandler ssh=ConnectHandler( device_type="cisco_ios", host="192.168.0.10", port=22, username="cisco", password="cisco" ) out=ssh.send_command("show run") print(ssh.find_prompt()) print("show run:\n"+out)
Operation:
- Netmiko Import: The ConnectHandler class is imported to handle the SSH connection.
- SSH Connection: Using the IP, port and credentials of the Cisco device, a connection is created.
- Command execution: The show run command is sent to obtain the current configuration of the device.
- Prompt printing: The device prompt is printed, indicating that the connection is still active.
- Configuration display: The command output is printed showing the running configuration.
This script is useful for performing quick configuration queries on Cisco devices in an automated manner.
2. Script to create, configure and assign IP addresses to VLANs:
from netmiko import ConnectHandler ssh = ConnectHandler( device_type="cisco_ios", host="192.168.10.2", port=22, username="womar1", password="womar" ) ssh.enable() comandos = [ "hostname uwu", "vlan 10", "interface vlan 10", "ip address 192.168.2.1 255.255.255.0", "no shutdown", 'interface range fa0/1 - 5', # Corrección aquí "switchport mode access", 'switchport access vlan 10', "vlan 20", "interface vlan 20", "ip address 192.168.3.1 255.255.255.0", "no shutdown", 'interface range fa0/6 - 10', # Corrección aquí "switchport mode access", 'switchport access vlan 20', "vlan 10", "interface vlan 30", "ip address 192.168.4.1 255.255.255.0", "no shutdown", 'interface range fa0/11 - 15', # Corrección aquí "switchport mode access", 'switchport access vlan 30', "vlan 10", "interface vlan 40", "ip address 192.168.5.1 255.255.255.0", "no shutdown", 'interface range fa0/16 - 20', # Corrección aquí "switchport mode access", 'switchport access vlan 40', "vlan 50", "interface vlan 50", "ip address 192.168.200.1 255.255.240.0", "no shutdown", 'interface range fa0/21 - 22', # Corrección aquí "switchport mode access", 'switchport access vlan 50', ] ssh.send_config_set(comandos) configuracion = ssh.send_command("show run") comands = ssh.find_prompt() print(comands) print("show run:\n" + configuracion)
Operation:
- Connection and privileged mode: An SSH connection is established and switched to privileged mode with ssh.enable().
- Command list: Several VLANs are created, interfaces and IP addresses are assigned to these VLANs, and the ports are configured in switchport mode access.
- Configuration application: Commands are sent in bulk with ssh.send_config_set().
- Configuration verification: The show run command is used to obtain the current configuration of the device.
- Printing the result: The device prompt and the resulting configuration are printed.
This script is ideal for automating the configuration of VLANs and assigning IPs to interfaces, facilitating the administration of complex networks quickly and efficiently.
Resources needed:
Before you start automating the configuration of Cisco devices using Python, it is important to ensure that you have the right environment. Here I detail the resources and tools you will need:
1. Installing Python and Libraries
You must have Python 3.6 or higher installed on your system. If you don't have it yet, you can easily install it depending on your operating system.
To interact with Cisco devices in an automated way, we use Netmiko, a Python library that facilitates SSH connection to routers and switches.
- Netmiko: It is the main library that we use to connect to network devices (such as routers or switches) through SSH.
- Paramiko: Netmiko depends on this library, which is an SSH client in Python.
- PIP: It is the Python package manager and you need it to install the libraries.
2. Installation of the Libraries
To install Netmiko and its dependencies (including Paramiko), run the following command in your terminal:
pip install netmiko
This command will download and install Netmiko along with its necessary dependencies. Once finished, you can check that everything has been installed correctly using:
pip list
This will show you all the installed libraries, among them you should see netmiko and paramiko.
3. SSH Access to Cisco Devices
In addition to the installed libraries, you need to make sure that the Cisco device (router or switch) is configured to accept SSH connections. Below are some key points to enable access:
a) Enable SSH on the Cisco device:
configure terminal ip domain-name cisco.local crypto key generate rsa username cisco privilege 15 secret cisco line vty 0 4 transport input ssh login local exit
b) Verify credentials and IP:
- Make sure you have the correct credentials (username and password) and that the device's IP address is accessible from the machine where you will run the Python scripts.
With these configurations, you are ready to run scripts and automate tasks on Cisco devices using Python.
Conclusion
With the right resources (Python, Netmiko, SSH enabled on Cisco devices) and the necessary libraries installed, you will be ready to start automating the configuration and management of your network devices using Python. Netmiko makes it easy to connect and execute commands on these devices, simplifying repetitive tasks and improving efficiency in network management.
The above is the detailed content of Cisco Automation with Python. For more information, please follow other related articles on the PHP Chinese website!

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download
The most popular open source editor

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
