【Python】CiscoルーターにTelnetしてログ取得

仕事で、CiscoルーターTelnetしてログ取得する事があるのですが

毎回Telnetしてコマンド叩いて..がめんどくさいので

Pythonの勉強がてら、簡単なプログラム作ってみました。

read.untilの使い方が良く分からないので、追々勉強します。

import getpass
import telnetlib

HOST = "192.168.0.100"
password = getpass.getpass() #Telnetパスワード
password2 = getpass.getpass() #特権パスワード

#192.168.0.100Telnet
tn = telnetlib.Telnet(HOST)

#Telnetパスワード
tn.read_until(b"Password:")
tn.write(password.encode("ascii") + b"\n")

#特権パスワード
#tn.read_until(b">")
tn.write(b"en"+ b"\n")
#tn.read_until(b"Password:")
tn.write(password2.encode("ascii")+b"\n")

# Ciscoコマンド発行
tn.write(b"show clock"+ b"\n")
tn.write(b"exit"+ b"\n")

#変数logに結果を保存
log = tn.read_all().decode("ascii")

file = open("log.txt","a") #テキストファイル作成
file.write(log) #log.txtに、結果を追記
file.close() #log.txt閉じる