機器一覧テキストを読み込んで、順次、コマンドを実行。結果をテキストで保存する。

logフォルダは予め作成しておく。
get-log.py
host_list.txt
log
取得されたファイル
log
internet-rtr01_20230219-0118-12.log
dist-rtr01_20230219-0118-21.log
dist-rtr02_20230219-0118-28.log
host_list.txt
#host or IP,username,password,device type
10.10.20.181,cisco,cisco,autodetect
10.10.20.175,cisco,cisco,cisco_ios_telnet
10.10.20.176,cisco,cisco,cisco_ios_telnet
get-log.py
import re
import os
from netmiko import ConnectHandler
currentdir = os.path.dirname(os.path.abspath(__file__))
filepath = os.path.join(currentdir,'host_list.txt')
#print(filepath)
with open(filepath) as f:
#1行ずつ読み込む
input_data = f.read().splitlines()
for rows in input_data:
#テキストの#行は読まない
if not re.match('#', rows):
row = rows.split(',')
HOST = row[0]
USERNAME = row[1]
PASSWORD = row[2]
DEVICETYPE = row[3]
# print(host, username,password)
# 接続パラメータを設定 device_typeを autodetect とする
remote_device = {'device_type': DEVICETYPE,
'host': HOST,
'username': USERNAME,
'password': PASSWORD,
}
print('Connecting to ' + HOST)
remote_host = ConnectHandler(**remote_device)
print('Entering enable mode ...')
remote_host.enable()
output = remote_host.send_command('show run')
prompt = remote_host.find_prompt()
hostname = prompt[:-1]
read_buf = output.split('\n')
read_buf = read_buf[3:]
config = '\n'.join(read_buf)
import datetime
#取得した日のタイムスタンプ
now = datetime.datetime.now()
today = now.strftime('%Y%m%d-%H%M-%S')
output_file = hostname + '_' + today + '.log'
output_file = os.path.join(currentdir,'log',output_file)
with open(output_file , 'w') as backup:
backup.write(config)
print('Backup of ' + hostname + ' completed successfully')
print('#' * 30)
remote_host.disconnect()
実行結果
Connecting to 10.10.20.181
Entering enable mode ...
Backup of internet-rtr01 completed successfully
##############################
Connecting to 10.10.20.175
Entering enable mode ...
Backup of dist-rtr01 completed successfully
##############################
Connecting to 10.10.20.176
Entering enable mode ...
Backup of dist-rtr02 completed successfully
##############################
PS C:\winpython>
取得ファイル(dist-rtr01_20230219-0118-21.log)
!
! Last configuration change at 16:15:15 UTC Sat Feb 18 2023
!
version 17.3
service timestamps debug datetime msec
service timestamps log datetime msec
service call-home
platform qfp utilization monitor load 80
no platform punt-keepalive disable-kernel-core
platform console serial
!
hostname dist-rtr01
!
boot-start-marker
boot-end-marker
!
~~ 省略 ~~
!
line con 0
exec-timeout 0 0
password cisco
stopbits 1
line vty 0 4
exec-timeout 720 0
password cisco
login local
transport input telnet ssh
!
restconf
end
他ファイルは同様なので省略。
コメント