Ssh connect to Cisco Catalyst with CentOS7 + Python3 + netmiko and save config locally

Overview

When I needed to write a program to access Cisco switches (Catalyst 2960 etc.) with ssh and automatically acquire the config, and collected information, it seems that it can be realized with a python library called netmiko, so I built an environment and created a program.

In addition, since the version of python that can be installed with yum in the default repository on CentOS 7 is 2 series and netmiko does not work as it is, the procedure for installing python3 is also described.

import

Add an IUS repository.

# yum install -y https://centos7.iuscommunity.org/ius-release.rpm

Verification

Execute the following command to check the minor versions that can be installed.

# yum search python3

Installation

Install the latest python3.6 (main unit + library, development, package management, etc.) at the moment.

# yum install -y python36u python36u-libs python36u-devel python36u-pip

# python -V
Python 3.6.8

# pip -V
pip 9.0.3 from /usr/lib/python3.6/site-packages (python 3.6)

installation of netmiko

Install the netmiko library.

# pip install netmiko

Sample program

Read the csv file that describes the IP address and password separated by commas as a sample program Write the python code that saves running-config in the specified directory.

devices.csv


192.168.1.254,password1234
172.16.1.254,password5678

backup.py


#!/usr/bin/env python

from netmiko import ConnectHandler
import csv
import datetime

#Date acquisition process to include the date in the config backup file
now = datetime.datetime.now()
today = now.strftime('%Y%m%d')

with open('devices.csv') as f:
        reader = csv.reader(f)

        #Read one line of csv file, get IP address and password, and turn the process
        for row in reader:
                cisco_ios = {
                        'device_type': 'cisco_ios', #For ssh, specify the left
                        'ip': row[0],               #First column of csv file
                        'username': 'user_name',    #Actual username
                        'password': row[1],         #Second column of csv file
                        'port' : 22,                #port number
                        'secret': row[1],           #enable secret password
                        'verbose': False,
                        }

                net_connect = ConnectHandler(**cisco_ios)

                #Move to privileged mode
                net_connect.enable()

                #Save running config to startup config with write memory command
                net_connect.send_command('wr')
                # running-Get config
                output = net_connect.send_command('show running-config')
                #Get the host name
                prompt = net_connect.find_prompt()
                hostname = prompt[:-1]

                #Exclude unnecessary lines at the beginning
                list = output.split('\n')
                list = list[3:]
                config = '\n'.join(list)

                #File name creation
                file = 'store/' + hostname + '-' + today + '.txt'

                #Save the file in the store directory
                with open(file, 'w') as backup:
                        backup.write(config)
                        print(hostname + ' : ' + 'succeeded')

                net_connect.disconnect()

Also, create a save destination directory for the config file.

# mkdir store

If you place the py file, csv file, and store directory in the same directory and execute the py file, the running config will be saved in the store directory in the format of "hostname-date.txt".

# ls
backup.py  devices.csv  store

# python backup.py
switch1 : succeeded
switch2 : succeeded

# ls store/
switch1-20200205.txt  switch2-20200205.txt

Recommended Posts

Ssh connect to Cisco Catalyst with CentOS7 + Python3 + netmiko and save config locally
Connect to BigQuery with Python
Connect to Wikipedia with Python
Connect realsense D435 to a PC with ubuntu 16.04 installed and save depth videos with python
screen and split screen with python and ssh login to remote server
Connect to centos6 on virtualbox with ssh connection from Mac
Python and Bash on Cisco Catalyst IOS-XE
Fractal to make and play with Python
A memo with Python2.7 and Python3 on CentOS
Connect to MySQL with Python within Docker
CentOS 6.4 with Python 2.7.3 with Apache with mod_wsgi and Django
Connect with mysql.connector with ssh tunnel in Python 3.7
Connect to s3 with AWS Lambda Python
Connect to pepper with PEPPER Mac's python interpreter
How to install python3 with docker centos
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
Note: Start Anaconda, enter the Python virtual environment, and connect locally to MongoDB.
Scraping tabelog with python and outputting to CSV
MessagePack-Try to link Java and Python with RPC
Template network config generation with Python and Jinja2
Connect to MySQL with Python on Raspberry Pi
Procedure to load MNIST with python and output to png
I tried to read and save automatically with VOICEROID2 2
I want to handle optimization with python and cplex
Try to operate DB with Python and visualize with d3
I tried to automatically read and save with VOICEROID2
Save lists, dictionaries and tuples to external files python
Something to enjoy with Prim Pro (X-Play) and Python
Introducing Python 2.7 to CentOS 6.6
Connect python to mysql
Easy to use Nifty Cloud API with botocore and python
How to install Python2.7 python3.5 with pyenv (on RHEL5 CentOS5) (2016 Nov)
kobitonote.py --Synchronize and save items edited with Kobito to Evernote
[Python] How to play with class variables with decorator and metaclass
How to connect to various DBs from Python (PEP 249) and SQLAlchemy
Send experiment results (text and images) to slack with Python
Try to bring up a subwindow with PyQt5 and Python
How to do Bulk Update with PyMySQL and notes [Python]
[Let's play with Python] Image processing to monochrome and dots
Save images on the web to Drive with Python (Colab)
Convert video to black and white with ffmpeg + python + opencv
I tried to make GUI tic-tac-toe with Python and Tkinter
Get additional data to LDAP with python (Writer and Reader)
How to log in to AtCoder with Python and submit automatically
Connect Raspberry Pi to Alibaba Cloud IoT Platform with Python
Connect a commercially available webcam to a PC with ubuntu 16.04 installed via USB and capture video with python
I was surprised at how to save objects with python, which is lean and very energy-saving.