銀狐NetDevOps-網絡運維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地址

[圖片上傳失敗...(image-660304-1621267283375)]

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

以上內容參考上一個小節銀狐DevNet-網絡運維Python初篇(三)讀取excel信息,批量抓取設備配置,基本沒變化。

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

# 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地址命名。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章