我試著用Python在Cisco設備上做些事.
這個練習是用Python去Telnet登入Cisco設備.
下面程式能做到:
1. Telnet(可選port).
2. 登入的設備清單用另外一份文件導入(txt).
3. 在python中手打要輸入進Cisco設備的指令.
4. Cisco設備執行結果用另外一份文件輸出(txt)
範例檔我是參考:
https://docs.python.org/3.6/library/telnetlib.html#telnet-example
首先先建立一個switches清單(SW_List.txt),
內容是switch IP, 如下範例.
192.168.80.201 192.168.80.202 192.168.80.203 192.168.80.204
再用Notepad++打下列的程式碼,
另存為PY_SWs_BK_v01.py. 我附上中文注釋方便好讀.
# -*- coding: UTF-8 -*-
# http://juilin77.blogspot.com/
# v20181008
# 下面程式能做到:
# 1. Telnet(可選port).
# 2. 登入的設備清單用另外一份文件導入(txt).
# 3. 在python中手打要輸入進Cisco設備的指令.
# 4. Cisco設備執行結果用另外一份文件輸出(txt)
# 首先導入下面這兩個模組
import getpass
import telnetlib
# 需要使用者手動輸入Telnet的Username
user = input("Enter your Telnet account: ")
password = getpass.getpass()
# 打開SW清單
f = open("SW_List.txt")
# 從SW_List中依次提取IP.
for IP in f:
IP = IP.strip()
print("Starting Backup Configuraion from SW: " + (IP))
# SW_List的IP等於HOST
# 這邊是加上port
HOST = IP
PORT = 23
# 自動代入剛才設定好的Host IP and port.
tn = telnetlib.Telnet()
tn.open(HOST,PORT)
# 要符合Cisco設備所出現的提示字元, 故改為Username:
tn.read_until(b"Username: ")
# user會代入剛才手動輸入的帳戶名
tn.write(user.encode('ascii') + b"\n")
if password:
# 要符合設備所出現的提示字元, Cisco設備會出現Password:
tn.read_until(b"Password: ")
# 把剛才手動輸入的密碼帶入
tn.write(password.encode('ascii') + b"\n")
# 這邊可以寫上我將要在登入設備後去執行的指令
tn.write(b"terminal length 0\n")
tn.write(b"show running-config\n")
tn.write(b"exit\n")
# 讀取Switch每一行的輸出
readoutput = tn.read_all()
# 打開一個檔案叫SW_BK_{ip address}.txt, 有寫入權限.
# newline=""是解決Windows換行符問題使用, Linux 不用這參數.
saveoutput = open("SW_BK_" + HOST + ".log", "w", newline="")
# 把Switch每一行的輸出寫進SW_BK_{ip address}.log
saveoutput.write(readoutput.decode('ascii'))
saveoutput.write("\n")
# 關閉文件
saveoutput.close
print(tn.read_all().decode('ascii'))
然後我用Web-IOU去建一個測試環境.

以下是預先需要設定的指令:
hostname MGMT_SW01 ! enable secret cisco123 ! no ip domain lookup ! username cisco privilege 15 password cisco123 ! interface vlan 1 ip address 192.168.80.201 255.255.255.0 no shutdown ! line vty 0 4 logging synchronous login local transport input all ! hostname SW(01-04) ! enable secret cisco123 ! no ip domain lookup ! username cisco privilege 15 password cisco123 ! interface vlan 1 ip address 192.168.80.(201-204) 255.255.255.0 no shutdown ! line vty 0 4 logging synchronous login local transport input all !
然後用Windows的cmd, 執行python.
D:\Tech\Python\PY_Cisco>python PY_SWs_BK_v01.py Enter your Telnet account: cisco Password: Starting Backup Configuraion from SW: 192.168.80.201 Starting Backup Configuraion from SW: 192.168.80.202 Starting Backup Configuraion from SW: 192.168.80.203 Starting Backup Configuraion from SW: 192.168.80.204 D:\Tech\Python\PY_Cisco>
完成
Check:


最初發表 / 最後更新: 2018.10.08 / 2018.10.08

0 comments:
張貼留言