圖片.png
# telnetlib.py
import telnetlib # telnetlib是Python標準模塊,可直接使用
import time
def get_config_command(filename):
ret = [] # 創建一個空列表
try: # 文件讀寫的異常處理
with open(filename) as f: # with語句處理文件,可自動關閉文件
lines = f.readlines() # readlines將文件每一行作為列表的一個元素
for line in lines: # 遍歷readlines方法返回的列表
ret.append(line.strip()) # 刪除列表元素中的換行符,追加到列表
return ret # 返回處理后的配置列表
except FileNotFoundError: # 如果沒有配置文件,打印異常
print("the file does not exist.")
def send_show_command(ip, username, password, commands):
print("telnet %s",ip)
with telnetlib.Telnet(ip) as tn:
tn.read_until(b"Username:")
tn.write(username.encode("ascii")+ b"\n")
tn.read_until(b"Password:")
tn.write(password.encode("ascii")+ b"\n")
tn.write(b"system-view"+ b"\n")
time.sleep(2)
for command in commands:
tn.write(command.encode("ascii") + b"\n")
time.sleep(1)
print(tn.read_very_eager().decode('ascii')) # 接收回顯
print("設備 %s 已經配置完成 !"%ip)
time.sleep(1)
if __name__ == "__main__":
devices_R = { # 保存路由器IP地址
"SZ1":"10.2.12.1",
"SZ2":"10.2.12.2",
}
devices_S = { # 保存交換機IP地址
"S4":"10.3.1.254",
"S1":"10.1.4.252",
"S2":"10.1.4.253"
}
username = "python"
password = "Huawei12#$"
config_file_R = "config_6_1_R.txt" # 路由器配置文件
config_file_S = "config_6_1_S.txt" # 交換機配置文件
commands_S = get_config_command(config_file_S) # 解析交換機配置命令
commands_R = get_config_command(config_file_R) # 解析路由器配置命令
for device in devices_R.keys(): # 配置路由器
ip = devices_R[device]
send_show_command(ip, username, password, commands_R)
for device in devices_S.keys(): # 配置交換機
ip = devices_S[device]
send_show_command(ip, username, password, commands_S)
# config_6_1_R.txt
aaa
local-user yunwei_001 cipher Huawei@123
local-user yunwei_001 service-type telnet
quit
user-interface vty 0 4
authentication-mode aaa
user privilege level 1
protocol inbound telnet
quit
ntp enable
ntp-service unicast-server 61.1.1.2
snmp-agent
snmp-agent sys-info version v3
snmp-agent mib-view nt include iso
snmp-agent mib-view rd include iso
snmp-agent mib-view wt include iso
snmp-agent group v3 group01 privacy read-view rd write-view wt notify-view nt
snmp-agent usm-user v3 user01 group01 authentication-mode sha Huawei@123 privacy-mode aes128 Huawei@123
# config_6_1_S.txt
aaa
local-user yunwei_001 password cipher Huawei@123
local-user yunwei_001 service-type telnet
quit
user-interface vty 0 4
authentication-mode aaa
user privilege level 1
protocol inbound telnet
quit
ntp-service unicast-server 61.1.1.2
snmp-agent
snmp-agent sys-info version v3
snmp-agent mib-view nt include iso
snmp-agent mib-view rd include iso
snmp-agent mib-view wt include iso
snmp-agent group v3 group01 privacy read-view rd write-view wt notify-view nt
snmp-agent usm-user v3 user01 group01 authentication-mode sha Huawei@123 privacy-mode des56 Huawei@123