日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

scrapy python3.8_银狐DevNet-网络运维Python初篇(四)netmiko抓取华为网络配置并存入本地...

發布時間:2025/3/21 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 scrapy python3.8_银狐DevNet-网络运维Python初篇(四)netmiko抓取华为网络配置并存入本地... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1、訓練場景:讀取excel中設備IP地址,通過Netmiko抓取設備配置,并存入本地

上一小節我們通過excel得到設備IP地址,并用Netmiko批量抓取設備配置并打印出來,真實運維場景我們需要把這些輸出的內容儲存起來,這也是我們本章的練習。

2、實驗環境:

操作系統:windows 10 PC機

python版本:python 3.8

網絡設備:華為CE 6865

編輯器:vscode(pycharm、sublime均可,推薦vscode)

excel格式:初次使用簡單一些,excel中只加入IP地址

3、思路分析

大部分都是上一小節內容,需要注意的是把配置文件存儲到本地時,我們需要打上一個時間戳,今天執行任務和明天執行代碼的配置要存入不同的文件夾,比如今天生成的配置就存在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()

執行結果-----------------------------------

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

有個小細節稍微分析一下:

# 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抓取設備配置使用了三種方式,最終使用的第三種,前兩個又有什么區別呢?我們在設備上show config時回顯內容太長經常看到--more--,第一種方式可以使用screen-length 0 temporary命令取消分屏顯示(不同廠商命令不同),第二種方式就是個別廠商直接no-more參數(華為CE和Juniper),直接取消分屏顯示。為什么我用的第三種方式什么都沒加呢?因為netmiko是默認取消分屏的,如果你以后使用paramiko或者其他第三方庫,這里需要注意一下。

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)

定義配置寫入文件的函數,需要2個外參,一個是get_config函數得到的內容,第二個就是設備的IP地址,方便我們給配置文件命名。

同事要設置時間戳,now=datatime.now()就是讀取當下時間,年月日時間引入date,幾點幾分引入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)

定義一個本地路徑/home/netops/linsy_env/netpro/,并附帶時間戳,便于區分是哪天的配置。并做一個判斷,假如2021-02-08文件夾已存在,證明今天這個文件夾下已生成過配置文件,那后續的配置文件都存入這個文件夾。如果2021-02-09不存在,那就先創建新的文件夾,在把網絡設備的配置文件存入。

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()

定義主函數,為了看下我們執行所有任務需要的時間,這里加入一下時間統計。(以后使用異步時會看出作用)代碼的頭部和尾部直接復制代碼就好,理解起來很容易,開頭記錄一下時間(starting_time = time() ),結尾記錄一下時間,相減就是代碼執行時間( time() - starting_time)。

其余代碼和上個小節差不多,需要注意函數write_config_to_file要傳入2個參數,一個是get_config函數得到的配置內容,第二個是傳入當前設備的IP地址,這樣我們生成配置文件時可以根據IP地址命名。

春節事情少一些,盡可能多更新,后續會逐漸加入異常處理,異步,一套代碼同事get多廠商設備等。

總結

以上是生活随笔為你收集整理的scrapy python3.8_银狐DevNet-网络运维Python初篇(四)netmiko抓取华为网络配置并存入本地...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。