銀狐NetDevOps-網(wǎng)絡(luò)運維Python初篇(四)netmiko抓取華為網(wǎng)絡(luò)配置并存入本地

科技銀狐

1、訓(xùn)練場景:讀取excel中設(shè)備IP地址,通過Netmiko抓取設(shè)備配置,并存入本地

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

2、實驗環(huán)境:

操作系統(tǒng):windows 10 PC機

python版本:python 3.8

網(wǎng)絡(luò)設(shè)備:華為CE 6865

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

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

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

3、思路分析

大部分都是上一小節(jié)內(nèi)容,需要注意的是把配置文件存儲到本地時,我們需要打上一個時間戳,今天執(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é)果-----------------------------------

image
image.png

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

以上內(nèi)容參考上一個小節(jié)銀狐DevNet-網(wǎng)絡(luò)運維Python初篇(三)讀取excel信息,批量抓取設(shè)備配置,基本沒變化。

有個小細節(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è)備配置使用了三種方式,最終使用的第三種,前兩個又有什么區(qū)別呢?我們在設(shè)備上show config時回顯內(nèi)容太長經(jīng)常看到--more--,第一種方式可以使用screen-length 0 temporary命令取消分屏顯示(不同廠商命令不同),第二種方式就是個別廠商直接no-more參數(shù)(華為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)

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

同事要設(shè)置時間戳,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/,并附帶時間戳,便于區(qū)分是哪天的配置。并做一個判斷,假如2021-02-08文件夾已存在,證明今天這個文件夾下已生成過配置文件,那后續(xù)的配置文件都存入這個文件夾。如果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)建新的配置文件,并要附帶時間戳,以便我們查看。(也是為了同一天多次備份配置時,配置文件不會因重復(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ù)需要的時間,這里加入一下時間統(tǒng)計。(以后使用異步時會看出作用)代碼的頭部和尾部直接復(fù)制代碼就好,理解起來很容易,開頭記錄一下時間(starting_time = time() ),結(jié)尾記錄一下時間,相減就是代碼執(zhí)行時間( time() - starting_time)。

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容