【Python】Ciscoルータ2台のログを自動で収集

2台のルータにアクセスして、showコマンドを実行。

出力結果は、ルータ毎にテキストファイルを作成して、保存。

 

#import getpass
import telnetlib

IPlist = ["192.168.0.100","192.168.0.101"] #ルーターIPアドレスリスト
password= "123" #Telnet用のパスワード
logx = ["R1","R2"] #ログファイル名


for x,y in zip(IPlist,logx):

tn = telnetlib.Telnet(x) #IPアドレスリストの先頭から順番にTelnet


tn.read_until(b"Password:") #Password:」表示まで待機
tn.write(password.encode("ascii")+ b"\n")#パスワード入力

#Ciscoコマンド実行
#tn.write(b"enable"+ b"\n")
#tn.read_until(b"Password:")
#tn.write(b"cisco"+ b"\n")



#show clockコマンド実行
tn.write(b"en"+ b"\n") #特権モード以降
tn.read_until(b"Password:") #Password:」表示まで待機
tn.write(b"123"+ b"\n") #特権パスワード入力
tn.write(b"ter len 0"+b"\n") #表示行数解放
tn.write(b"show clock" + b"\n")
tn.write(b"show running-config"+ b"\n")
tn.write(b"exit"+b"\n")


#出力結果をout変数に保存
out = (tn.read_all().decode("ascii")) #出力結果を「out」変数に保存

log1 = open(y+"ログ.txt","a") #ログ保存用のテキストファイル作成(末尾に追記)
log1.write(out) #出力結果をテキストファイルに書き込み
log1.close() #テキストファイル閉じる