scrapy python3.8_银狐DevNet-网络运维Python初篇(四)netmiko抓取华为网络配置并存入本地...
1、訓(xùn)練場(chǎng)景:讀取excel中設(shè)備IP地址,通過(guò)Netmiko抓取設(shè)備配置,并存入本地
上一小節(jié)我們通過(guò)excel得到設(shè)備IP地址,并用Netmiko批量抓取設(shè)備配置并打印出來(lái),真實(shí)運(yùn)維場(chǎng)景我們需要把這些輸出的內(nèi)容儲(chǔ)存起來(lái),這也是我們本章的練習(xí)。
2、實(shí)驗(yàn)環(huán)境:
操作系統(tǒng):windows 10 PC機(jī)
python版本:python 3.8
網(wǎng)絡(luò)設(shè)備:華為CE 6865
編輯器:vscode(pycharm、sublime均可,推薦vscode)
excel格式:初次使用簡(jiǎn)單一些,excel中只加入IP地址
3、思路分析
大部分都是上一小節(jié)內(nèi)容,需要注意的是把配置文件存儲(chǔ)到本地時(shí),我們需要打上一個(gè)時(shí)間戳,今天執(zhí)行任務(wù)和明天執(zhí)行代碼的配置要存入不同的文件夾,比如今天生成的配置就存在2021-02-08的文件件下,明天生成的配置都存入2021-02-09的文件件下。
4、整體代碼
#!/usr/bin/env python
#coding: utf-8
import os
from time import time
from datetime import datetime
from netmiko import ConnectHandler
from openpyxl import Workbook
from openpyxl import load_workbook
def read_device_excel( ):
ip_list = []
wb1 = load_workbook('/home/netops/venv/cs_lab.xlsx')
ws1 = wb1.get_sheet_by_name("Sheet1")
for cow_num in range(2,ws1.max_row+1):
ipaddr = ws1["a"+str(cow_num)].value
ip_list.append(ipaddr)
return ip_list
def get_config(ipaddr):
session = ConnectHandler(device_type="huawei",
ip=ipaddr,
username="dev_user",
password="dev_password",
banner_timeout=300)
print("connecting to "+ ipaddr)
print ("---- Getting HUAWEI configuration from{}-----------".format(ipaddr))
# config_data = session.send_command('screen-length 0 temporary')
# config_data = session.send_command('dis cu | no-more ')
config_data = session.send_command("dis cu")
session.disconnect()
return config_data
def write_config_to_file(config_data,ipaddr):
now = datetime.now()
date= "%s-%s-%s"%(now.year,now.month,now.day)
time_now = "%s-%s"%(now.hour,now.minute)
#---- Write out configuration information to file
config_path = '/home/netops/linsy_env/netpro/' +date
verify_path = os.path.exists(config_path)
if not verify_path:
os.makedirs(config_path)
config_filename = config_path+"/"+'config_' + ipaddr +"_"+date+"_" + time_now # Important - create unique configuration file name
print ('---- Writing configuration: ', config_filename)
with open( config_filename, "w",encoding='utf-8' ) as config_out:
config_out.write( config_data )
return
def main():
starting_time = time()
ip_list = read_device_excel()
for ipaddr in ip_list:
hwconfig = get_config(ipaddr)
write_config_to_file(hwconfig,ipaddr)
print ('\n---- End get config threading, elapsed time=', time() - starting_time)
#========================================
# Get config of HUAWEI
#========================================
if __name__ == '__main__':
main()
執(zhí)行結(jié)果-----------------------------------
5、代碼詳解
#!/usr/bin/env python
#coding: utf-8
import os
from time import time
from datetime import datetime
from netmiko import ConnectHandler
from openpyxl import Workbook
from openpyxl import load_workbook
def read_device_excel( ):
ip_list = []
wb1 = load_workbook('/home/netops/venv/cs_lab.xlsx')
ws1 = wb1.get_sheet_by_name("Sheet1")
for cow_num in range(2,ws1.max_row+1):
ipaddr = ws1["a"+str(cow_num)].value
ip_list.append(ipaddr)
return ip_list
def get_config(ipaddr):
session = ConnectHandler(device_type="huawei",
ip=ipaddr,
username="dev_user",
password="dev_password",
banner_timeout=300)
print("connecting to "+ ipaddr)
print ("---- Getting HUAWEI configuration from {}-----------".format(ipaddr))
# config_data = session.send_command('screen-length 0 temporary')
# config_data = session.send_command('dis cu | no-more ')
config_data = session.send_command("dis cu")
session.disconnect()
return config_data
有個(gè)小細(xì)節(jié)稍微分析一下:
# config_data = session.send_command('screen-length 0 temporary')
# config_data = session.send_command('dis cu | no-more ')
config_data = session.send_command("dis cu")
可以看到netmiko抓取設(shè)備配置使用了三種方式,最終使用的第三種,前兩個(gè)又有什么區(qū)別呢?我們?cè)谠O(shè)備上show config時(shí)回顯內(nèi)容太長(zhǎng)經(jīng)常看到--more--,第一種方式可以使用screen-length 0 temporary命令取消分屏顯示(不同廠商命令不同),第二種方式就是個(gè)別廠商直接no-more參數(shù)(華為CE和Juniper),直接取消分屏顯示。為什么我用的第三種方式什么都沒(méi)加呢?因?yàn)閚etmiko是默認(rèn)取消分屏的,如果你以后使用paramiko或者其他第三方庫(kù),這里需要注意一下。
def write_config_to_file(config_data,ipaddr):
now = datetime.now()
date= "%s-%s-%s"%(now.year,now.month,now.day)
time_now = "%s-%s"%(now.hour,now.minute)
定義配置寫(xiě)入文件的函數(shù),需要2個(gè)外參,一個(gè)是get_config函數(shù)得到的內(nèi)容,第二個(gè)就是設(shè)備的IP地址,方便我們給配置文件命名。
同事要設(shè)置時(shí)間戳,now=datatime.now()就是讀取當(dāng)下時(shí)間,年月日時(shí)間引入date,幾點(diǎn)幾分引入time_now。
config_path = '/home/netops/linsy_env/netpro/' +date
verify_path = os.path.exists(config_path)
if not verify_path:
os.makedirs(config_path)
定義一個(gè)本地路徑/home/netops/linsy_env/netpro/,并附帶時(shí)間戳,便于區(qū)分是哪天的配置。并做一個(gè)判斷,假如2021-02-08文件夾已存在,證明今天這個(gè)文件夾下已生成過(guò)配置文件,那后續(xù)的配置文件都存入這個(gè)文件夾。如果2021-02-09不存在,那就先創(chuàng)建新的文件夾,在把網(wǎng)絡(luò)設(shè)備的配置文件存入。
config_filename = config_path+"/"+'config_' + ipaddr +"_"+date+"_" + time_now # Important - create unique configuration file name
print ('---- Writing configuration: ', config_filename)
with open( config_filename, "w",encoding='utf-8' ) as config_out:
config_out.write( config_data )
return
定義配置文件的名稱,注意是在提前定義好的路徑下創(chuàng)建新的配置文件,并要附帶時(shí)間戳,以便我們查看。(也是為了同一天多次備份配置時(shí),配置文件不會(huì)因重復(fù)而覆蓋)
def main():
starting_time = time()
ip_list = read_device_excel()
for ipaddr in ip_list:
hwconfig = get_config(ipaddr)
write_config_to_file(hwconfig,ipaddr)
print ('\n---- End get config threading, elapsed time=', time() - starting_time)
#========================================
# Get config of HUAWEI
#========================================
if __name__ == '__main__':
main()
定義主函數(shù),為了看下我們執(zhí)行所有任務(wù)需要的時(shí)間,這里加入一下時(shí)間統(tǒng)計(jì)。(以后使用異步時(shí)會(huì)看出作用)代碼的頭部和尾部直接復(fù)制代碼就好,理解起來(lái)很容易,開(kāi)頭記錄一下時(shí)間(starting_time = time() ),結(jié)尾記錄一下時(shí)間,相減就是代碼執(zhí)行時(shí)間( time() - starting_time)。
其余代碼和上個(gè)小節(jié)差不多,需要注意函數(shù)write_config_to_file要傳入2個(gè)參數(shù),一個(gè)是get_config函數(shù)得到的配置內(nèi)容,第二個(gè)是傳入當(dāng)前設(shè)備的IP地址,這樣我們生成配置文件時(shí)可以根據(jù)IP地址命名。
春節(jié)事情少一些,盡可能多更新,后續(xù)會(huì)逐漸加入異常處理,異步,一套代碼同事get多廠商設(shè)備等。
總結(jié)
以上是生活随笔為你收集整理的scrapy python3.8_银狐DevNet-网络运维Python初篇(四)netmiko抓取华为网络配置并存入本地...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python将索引升序_程序在Pytho
- 下一篇: 升级python版本_升级python版