LoginSignup
3
4

More than 3 years have passed since last update.

【Python】ルーターやスイッチでshow ip int bを定期的にcsv出力する

Posted at

はじめに

netmikoはネットワーク機器にSSH接続するためのPythonモジュールです。

netmikoのコマンド実行結果は非構造化データです。
TextFSMntc-templatesを利用して、構造化データに変換できるのでcsvにきれいに保存できます。ntc-templatesは様々なネットワーク機器のshowコマンド解析結果を構造化データに変換するためのテンプレート集です。

ntc-templatesのダウンロード

  • ここからzipをダウンロードします
  • ホームディレクトリ(Windowsならユーザーのディレクトリ)に展開します
  • フォルダ名をntc-templates-masterからntc-templatesに変更

Netmikoが自動で~/ntc-templates/templates/indexを参照してくれます。

コード

netmikoなどのpip installはお忘れなく!

$ pip install netmiko
$ pip install schedule

以下ソースです。

ssib.py
import netmiko
import pprint
import time
import schedule
import csv

def SIIB():
  device = {'device_type': 'cisco_ios',
            'host': 'Cisco1',
            'ip': 'ネットワーク機器のIP',
            'username': '入力',
            'password': '入力',
            'secret':   'cisco'}

  print('Connecting...')
  conn = netmiko.ConnectHandler(**device)

  print('Enable...')
  conn.enable()

  print('Execute command...')
  # コマンド実行(TextFSMを有効にしてパース)
  result = conn.send_command('show ip interface brief', use_textfsm=True)

  print('SIIB done')
  header = result[0].keys()

  print('SIIB write')
  # DictWriterを使用してCSV形式で出力
  with open('保存ファイル名', 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=header, lineterminator='\n')
    writer.writeheader()        # ヘッダ出力
    writer.writerows(result)   # 結果出力

  print('Disconnecting...')
  conn.disconnect()

#以下はscheduleモジュールを使った定期実行部分。
#Ctrl Cで止められます

#一分毎に実行
schedule.every(1).minutes.do(SIIB)

while True:
  schedule.run_pending()
  time.sleep(1)



作っていて困ったこと

  • scheduleがちょっと特徴あるなと思いました

まとめ

netmikoは各ベンダーのコマンドをそのまま使えて便利ですね。
反面、各ベンダー毎にコードを書く手間が出てきそうです。
同じpythonモジュールのnapalmは異なるベンダー機器に対して共通のコマンドを使えるようです。便利そう。

3
4
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
3
4