我試著用Python在Cisco設備上做些事.
這個練習是用Python去Telnet登入Cisco設備.
下面程式能做到:
1. Telnet(可選port).
2. 手動輸入Telnet的帳密.
3. 在python中手打要輸入進Cisco設備的指令
4. 用loop讓Switch反復執行建立多個VLANs
範例檔我是參考:
https://docs.python.org/3.6/library/telnetlib.html#telnet-example
用Notepad++打下列的程式碼,
另存為PY_VLANS_v01.py. 我附上中文注釋方便好讀.
# -*- coding: UTF-8 -*-
# http://juilin77.blogspot.com/
# v20181005
# 下面程式能做到:
# 1. Telnet(可選port).
# 2. 手動輸入Telnet的帳密.
# 3. 在python中手打要輸入進Cisco設備的指令.
# 4. 用loop讓Switch反復執行建立多個VLANs.
# 首先導入下面這兩個模組
import getpass
import telnetlib
# 修改localhost為你要登入主機的IP
# 這邊是加上port
HOST = "192.168.80.191"
PORT = 23
# 需要使用者手動輸入Telnet的Username
user = input("Enter your Telnet account: ")
password = getpass.getpass()
# 自動代入剛才設定好的host IP and port.
tn = telnetlib.Telnet()
tn.open(HOST,PORT)
# 要符合Cisco設備所出現的提示字元, 故改為Username:
tn.read_until(b"Username: ")
# user會代入在Line 13手動輸入的帳戶名
tn.write(user.encode('ascii') + b"\n")
if password:
# 要符合設備所出現的提示字元, Cisco設備會出現Password:
tn.read_until(b"Password: ")
# 把Line 14手動輸入的密碼帶入
tn.write(password.encode('ascii') + b"\n")
# 這邊可以寫上我將要在登入設備後去執行的指令
tn.write(b"enable\n")
tn.write(b"cisco123\n")
tn.write(b"configure terminal\n")
# 我用loop的方式, 建立多個VLAN, 從VLAN2開始, 從VLAN2開始, 建立到VLAN4.
# VALN name 就是 PY_VLAN_開頭, 後面接上VLAN ID.
for n in range(2,5):
tn.write(b"vlan " + str(n).encode('ascii') + b"\n")
tn.write(b"name PY_VLAN_" + str(n).encode('ascii') + b"\n")
tn.write(b"end\n")
tn.write(b"exit\n")
print(tn.read_all().decode('ascii'))
然後我用Web-IOU去建一個測試環境.
以下是預先需要設定的指令:
hostname SW01 ! enable secret cisco123 ! no ip domain lookup ! username cisco password 0 cisco123 ! interface vlan 1 ip address 192.168.80.191 255.255.255.0 no shutdown ! line vty 0 4 logging synchronous login local transport input all !
然後用Windows的cmd, 執行python.
C:\Windows\System32>cd C:\Users\Peter\Desktop\Python\PY_Cisco C:\Users\Peter\Desktop\Python\PY_Cisco>python PY_VLANS_v01.py Enter your Telnet account: cisco Password: SW01>enable Password: SW01#configure terminal Enter configuration commands, one per line. End with CNTL/Z. SW01(config)#vlan 2 SW01(config-vlan)#name PY_VLAN_2 SW01(config-vlan)#vlan 3 SW01(config-vlan)#name PY_VLAN_3 SW01(config-vlan)#vlan 4 SW01(config-vlan)#name PY_VLAN_4 SW01(config-vlan)#end SW01#exit C:\Users\Peter\Desktop\Python\PY_Cisco>
完成
Check:
最初發表 / 最後更新: 2018.10.05 / 2018.10.08



0 comments:
張貼留言