スレッドでNetmikoのコマンド収集を高速化してみました。
以前に書いたCisco機器のコマンド収集のPythonスクリプト↓
なのですが、百台以上の機器からコマンド出力を収集するには時間がかかりました。何台か並列でできないかと思いいろいろ調べたところ以下の記事でスレッドという手法があることを知りました。
ITエンジニアがときめく自動化の魔法 ~仕事を効率化したくなる自動化テクニック~
- 作者:敏克, 増井
- 発売日: 2020/08/26
- メディア: 単行本
上記の記事を参考にして以下のコードを作成しました。
いろいろ突込みどころはあるとは思いますが、並列で動いてくれて
前回のものよりかなり早く処理を行ってくれました。
from concurrent.futures import ThreadPoolExecutor from netmiko import ConnectHandler import time import csv import threading def run_show_cmd(host_name, host_ip, d_type): cisco = { 'device_type': d_type, 'ip': host_ip, 'username': 'xxxxx', 'password': 'xxxx', 'secret': 'xxxx', 'verbose': False, } net_connect = ConnectHandler(**cisco) net_connect.enable() output1 = net_connect.send_command("show run | inc hostname") output2 = net_connect.send_command("show env") output3 = net_connect.send_command("show env") net_connect.disconnect() output = "##############" + host_name + "##############" + "\n" + output1 + "\n" + output2 + "\n" + output3 +"\n\n" print(output) def auto_login(host_name, host_ip): i = host_name j = host_ip try: run_show_cmd(i, j, "cisco_ios") except: try: run_show_cmd(i, j, "cisco_ios_telnet") except: print("##############", host_name, "##############") print("Login failed to ", host_name) print("") tpe = ThreadPoolExecutor(max_workers=5) with open('device-list.csv') as f: reader = csv.reader(f) for r in reader: host_name = r[0] host_ip = r[1] tpe.submit(auto_login, host_name, host_ip)
- 作者:Lorin Hochstein
- 発売日: 2016/04/16
- メディア: 大型本