LoginSignup
1
2

More than 3 years have passed since last update.

CentOS7 + Python3 + netmikoでCisco Catalystにssh接続してローカルにコンフィグを保存する

Last updated at Posted at 2020-02-05

概要

Ciscoのスイッチ(Catalyst2960など)にsshアクセスしコンフィグを自動で取得するプログラムを書く必要が生じ情報収集すると、どうもnetmikoというpythonライブラリで実現できそうなので環境構築しプログラムを作成してみました。

なおCentOS7にデフォルトのリポジトリでyumインストールできるpythonのヴァージョンは2系でそのままではnetmikoが動作しないため、python3をインストールする手順も記載します。

インポート

IUSリポジトリを追加します。

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

確認

以下コマンドを実行しインストール可能なマイナーヴァージョンを確認します。

# yum search python3

インストール

現時点で最新のpython3.6(本体+ライブラリ、開発、パッケージ管理等)をインストールします。

# 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)

netmikoのインストール

netmikoライブラリをインストールします。

# pip install netmiko

サンプルプログラム

サンプルプログラムとしてIPアドレスとパスワードをカンマ区切りで記載したcsvファイルを読み込み
running-configを指定ディレクトリに保存するpythonコードを記載します。

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

# コンフィグのバックアップファイルに日付を含ませるための日付取得処理
now = datetime.datetime.now()
today = now.strftime('%Y%m%d')

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

        # csvファイルを1行読み込んでIPアドレスとパスワードを取得し処理を回す
        for row in reader:
                cisco_ios = {
                        'device_type': 'cisco_ios', # sshの場合左記を指定
                        'ip': row[0],               # csvファイルの1カラム目
                        'username': 'user_name',    # 実際のユーザー名
                        'password': row[1],         # csvファイルの2カラム目
                        'port' : 22,                # ポート番号
                        'secret': row[1],           # enable secretのパスワード
                        'verbose': False,
                        }

                net_connect = ConnectHandler(**cisco_ios)

                # 特権モードに移行
                net_connect.enable()

                # write memoryコマンドでrunning configをstartup configに保存
                net_connect.send_command('wr')
                # running-configの取得
                output = net_connect.send_command('show running-config')
                # ホスト名の取得
                prompt = net_connect.find_prompt()
                hostname = prompt[:-1]

                # 先頭の不要行を除外
                list = output.split('\n')
                list = list[3:]
                config = '\n'.join(list)

                # ファイル名の作成
                file = 'store/' + hostname + '-' + today + '.txt'

                # ファイルをstoreディレクトリに保存
                with open(file, 'w') as backup:
                        backup.write(config)
                        print(hostname + ' : ' + 'succeeded')

                net_connect.disconnect()

またコンフィグファイルの保存先ディレクトリを作成しておきます。

# mkdir store

pyファイルとcsvファイル、storeディレクトリを同じディレクトリに設置しpyファイルを実行するとstoreディレクトリに「ホスト名-年月日.txt」の形式でrunning configが保存されます。

# ls
backup.py  devices.csv  store

# python backup.py
switch1 : succeeded
switch2 : succeeded

# ls store/
switch1-20200205.txt  switch2-20200205.txt
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2