Python如何實現(xiàn)網(wǎng)絡(luò)自動化運維華為設(shè)備
Python網(wǎng)絡(luò)自動化運維華為設(shè)備
本文將講述使用Python實現(xiàn)華為設(shè)備的網(wǎng)絡(luò)自動化運維。
本次運維是基于Python 3.11環(huán)境,需要提前安裝paramiko和ncclient第三方庫。
使用eNSP仿真模擬器來模擬真實環(huán)境的拓撲圖
首先需要保證宿主機與模擬器內(nèi)的網(wǎng)絡(luò)互通
我這里使用了192.168.10.0/24的本地適配器作為橋接網(wǎng)卡
測試互通性效果如下:
接下來配置登錄LSW4交換機設(shè)備的本地賬戶
int vlan 1 ip add 192.168.10.2 24 //配置VLANif 1的地址用來連接設(shè)備 user-interface vty 0 4 authentication-mode aaa //將虛擬遠程登錄的模式設(shè)置為AAA認證 protocol inbound ssh //使能SSH協(xié)議連接功能 user privilege level 15 //用戶權(quán)限為15,這是最高權(quán)限 quit stelnet server enable //使能設(shè)備stelnet服務(wù)的功能 ssh user test //配置SSH用戶test ssh user test service-type stelnet //將用戶的服務(wù)類型改為stelnet ssh user test authentication-type password //將SSH用戶test的登錄模式改為密碼模式 aaa //進入AAA視圖 local-user test password cipher Huawei@123 //配置test賬戶的密碼 local-user test privilege level 15 //配置test賬號的權(quán)限為15 local-user test service-type ssh //配置SSH賬戶的權(quán)限為SSH //以上是connect和command模塊 sftp server enable //使能SFTP服務(wù) ssh user test service-type all //開啟test全部的服務(wù) ssh user test sftp-directory flash: //將用戶test的sftp下載目錄指定為flash:下 //以上是download模塊
配置LSW6的聚合鏈路和OSPF協(xié)議用以測試
int eth-tr 1 mode lacp trunkport g0/0/1 trunkport g0/0/2 //配置聚合鏈路 int vlan 1 ip add 192.168.10.4 24 //使用該地址登錄設(shè)備 ospf area 0 net 0.0.0.0 0.0.0.0 //與LSW4建立OSPF鄰居關(guān)系
LSW4上也要進行相應(yīng)OSPF和聚合鏈路的配置
interface Eth-Trunk1 mode lacp-static # interface GigabitEthernet0/0/2 eth-trunk 1 # interface GigabitEthernet0/0/3 eth-trunk 1 //聚合鏈路 ospf 1 area 0.0.0.0 network 0.0.0.0 255.255.255.255 //配置OSPF協(xié)議
接下來進行CE2設(shè)備的配置
該設(shè)備主要用來進行netconf的功能測試
int vlan 1 ip add 192.168.10.3 24 //配置登錄地址 int g1/0/0 undo shut //開啟接口 stelnet server enable //使能stelnet服務(wù) user-interface vty 0 4 authentication-mode aaa protocol inbound ssh //將遠程登錄模式設(shè)置為AAA模式,開啟SSH登錄功能 aaa local-user netconf password cipher Huawei@123 local-user netconf service-type ssh local-user netconf level 3 //創(chuàng)建一個netconf賬戶,密碼為Huawei@123,服務(wù)類型為SSH,權(quán)限為3 # ssh user netconf ssh user netconf authentication-type password ssh user netconf service-type snetconf //將用戶netconf的認證類型改為密碼類型,服務(wù)類型改為snetconf 將 # netconf protocol inbound ssh port 830 //netconf的端口號為830,允許netconf通過830號端口連接 q # snetconf server enable //使能snetconf服務(wù)
下載好第三方庫
ncclient,paramiko
在PyCharm環(huán)境內(nèi)引入對應(yīng)的庫
import re,time,paramiko from datetime import datetime from config import parameter_dict,netconf1 from ncclient import manager from ncclient.xml_ import to_ele from threading import Thread
創(chuàng)建一個類
里面定義并實現(xiàn)六個功能模塊:
class SW: def __init__(self): //初始化,建立起與設(shè)備的SSH連接。 self.session = paramiko.SSHClient() self.session.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.session.connect(hostname='192.168.10.2',password='Huawei@123',username='test',port=22,allow_agent=False,look_for_keys=False) self.vty = self.session.invoke_shell() self.command('sc 0 te') print('連接成功') def command(self,command): //向網(wǎng)絡(luò)設(shè)備終端輸入變量并輸出回顯,回顯字符上限為999999,類型為utf-8 self.vty.send(command+'\n') time.sleep(1) return self.vty.recv(999999).decode('utf-8') def parameter_info(self): //定義監(jiān)控數(shù)據(jù)參數(shù)方法,每個5分鐘輸出一次設(shè)備參數(shù) parameter_list = [] while True: for i in parameter_dict.keys(): pat = self.command(parameter_dict[i]['command']) print(pat) res = re.compile(parameter_dict[i]['re']).findall(pat) print(res) if i == 'fan': res = res if res else "All are fans faulty" parameter_list.append(f'{i}:{res}') print('\n'.join(parameter_list)) time.sleep(60 * 5) def download(self): //通過SFTP功能下載flash:/vrpcfg.zip文件,并每隔一天保存在本地W:\\TestPython文件夾內(nèi) while True: with paramiko.Transport(('192.168.10.2',22)) as t: t.connect(username='test',password='Huawei@123') sftp = paramiko.SFTPClient.from_transport(t) sftp.get('/vrpcfg.zip',f'W:\\TestPython\\{datetime.now().strftime("%Y_%m_%d_%H_%M_%S")}.zip') print('下載成功') time.sleep(60 * 60 * 24) def netconf(self,xml): //最后配置日志文件地址為10.1.60.2 manager.connect(host='192.168.10.3',port=22,username='netconf',password="Huawei@123",allow_agent=False,hostkey_verify=False,device_params={"name":"huawei"}).rpc(to_ele(xml)) print("設(shè)置成功") def start(self): //定義多進程模塊 Thread(target=self.download).start() Thread(target=self.parameter_info).start() if __name__ == "__main__": //滿足條件則運行該文件 for i in netconf1.values(): SW().start() SW().netconf(i)
需要配置一個名為config的xml文件
內(nèi)容如下所示,運行后會查看該設(shè)備的風扇狀態(tài),電源狀態(tài),CPU利用率,內(nèi)存使用率,OSPF鄰居狀態(tài),以及聚合鏈路狀態(tài)。
parameter_dict = { "fan" : {"command":"display fan","re":"Normal"}, "power" : {"command":"display power","re":"Supply|NotSupply|Sleep|No"}, "cpu" : {"command":"display cpu-usage","re":"CPU Usage : .+?%"}, "memory" : {"command":"display memory","re":"Memory Using Percentage Is: .+?%"}, "ospf" : {"command":"display ospf peer brief","re":"down|init|2-way|exstart|exchange|loading|Full"}, "lacp" : {"command":"display eth-trunk","re":"Up|Down"} } netconf1 = { 'host_log': ''' <edit-config> <target> <running/> </target> <default-operation>merge</default-operation> <error-option>rollback-on-error</error-option> <config> <syslog xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <syslogServers> <syslogServer operation="merge"> <ipType>ipv4</ipType> <serverIp>10.1.60.2</serverIp> <isDefaultVpn>false</isDefaultVpn> <vrfName>_public_</vrfName> <timestamp>UTC</timestamp> <transportMode>tcp</transportMode> </syslogServer> </syslogServers> </syslog> </config> </edit-config> '''}
運行后就可以輸出網(wǎng)絡(luò)設(shè)備終端的回顯內(nèi)容了
以下是回顯截圖:
SFTP本地下載設(shè)備狀態(tài)到指定路徑測試
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python中np.random.permutation函數(shù)實例詳解
np.random.permutation是numpy中的一個函數(shù),它可以將一個數(shù)組中的元素隨機打亂,返回一個打亂后的新數(shù)組,下面這篇文章主要給大家介紹了關(guān)于python中np.random.permutation函數(shù)的相關(guān)資料,需要的朋友可以參考下2023-04-04