Python Netmiko脚本 定时备份 网络设备配置

用在没有安装Python解析器的Windows桌面系统上进行定时备份网络设备配置。

因多线程在编译为exe文件后容易出现问题,故采用单线程方式。

Python开发版本: 3.8.10。

3.8往上版本不支持Win7。

复制下列文字保存为 requirements.txt,然后运行 pip install -r requirements.txt。(pip或pip3)

        pip install netmiko

使用方法:

device_list里面写--设备IP、用户名、密码、enable密码、设备类型

# !/usr/bin/python3
# -*- coding=utf-8 -*-
# @Author  : zunsi
# @file: netmiko_backup_configure_file.py
# @time: 2020-05-25  09:59:24


# python3.8
# pip install netmiko


import os, time
from datetime import datetime
from netmiko import ConnectHandler


device_list = ['100.100.1.1 username password enablepassword(没有则为 null) juniper',
               '100.100.1.3 username password enablepassword h3c',
               '100.100.100.101 username password enablepassword h3c',
               '100.100.100.102 username password enablepassword h3c',
               '100.100.100.103 username password enablepassword h3c',
               '100.100.203.2 username password enablepassword aruba']
               
now = datetime.now()
time_now = "%i-%.2i-%.2i_%.2i%.2i%.2i" % (now.year, now.month, now.day, now.hour, now.minute, now.second)
backfile = time_now + '_NetBak_File'
log_name = 'NetBakError.log'
path_log = os.path.join(backfile, log_name)
connect_exc = True

for i in device_list:
    ipaddr = i.split(' ')[0]
    username = i.split(' ')[1]
    password = i.split(' ')[2]
    enable_password = i.split(' ')[3]
    vendor = i.split(' ')[4]

    if vendor.lower() == 'juniper':
        device_type = 'juniper_junos'
        backup_command = 'show configuration | display set'
    elif vendor.lower() == 'cisco':
        device_type = 'cisco_ios'
        backup_command = 'show running-config'
    elif vendor.lower() == 'h3c':
        device_type = 'hp_comware'
        backup_command = 'display current-configuration'
    elif vendor.lower() == 'aruba':
        device_type = 'aruba_os'
        backup_command = 'show running-config '

    try:
        if not os.path.exists(backfile):
            os.makedirs(backfile)
    except:
        print('Unknow Error !!!')

    print('^ ' * 35)
    print('\n开始从 {} 备份配置\n'.format(ipaddr))
    print(str(datetime.now()) + ' >>> Connection to device {}\n'.format(ipaddr))

    try:
        net_connect = ConnectHandler(device_type=device_type,
                                     ip=ipaddr,
                                     username=username,
                                     password=password,
                                     secret=enable_password)
        net_connect.enable()
        time.sleep(1)
        running_config = net_connect.send_command(backup_command)
    except Exception as e:
        print(str(datetime.now()) + ' >>> Connection to device {} '.format(ipaddr) + ' Error !!\n')
        with open(path_log, 'a+') as f:
            f.write(str(datetime.now()) + ' >>>  ' + str(e) + '\n')
        connect_exc = False
        break

    print(str(datetime.now()) + ' >>> Saving config from device {}\n'.format(ipaddr))

    filename ="%s_%i-%.2i-%.2i_%.2i%.2i%.2i.cfg" % (ipaddr.replace('.', '-'), now.year, now.month, now.day, now.hour, now.minute, now.second)
    path_name = os.path.join(backfile, filename)
    if connect_exc:
        with open(path_name, 'w') as f:
            f.write(running_config)
        print(str(datetime.now()) + ' >>> {} Configuration backup complete !\n'.format(ipaddr))
        print('=' * 70)
    else:
        print('连接错误,请检查设备地址,用户名密码等等 !')
        break

print('\n 网络设备配置备份完成 , 3秒后退出...........')

time.sleep(3)

打包成exe文件,:

        安装 pyinstaller及其依赖 pywin32(点我下载)

                pip install pyinstaller

        打包成exe ,没有控制台黑窗口:

                pyinstaller -F -w D:\project\test.py 

                参数含义:

                        -F 指定打包后只生成一个exe格式的文件(建议写上这个参数)

                        -D –onedir 创建一个目录,包含exe文件,但会依赖很多文件(默认选项)

                        -c –console, –nowindowed 使用控制台,无界面(默认)

                        -w –windowed, –noconsole 使用窗口,无控制台

                        -p 添加搜索路径,让其找到对应的库。

                        -n  打包后新的程序名称

                        -i 改变生成程序的icon图标(可以换个好看的图标)

Windows定时任务:

        Windows 定时执行脚本_OnebyWang的博客-CSDN博客_windows定时执行脚本

效果:

 

如果帮到你了,可以点个赞么!

posted @   kleinscnb  阅读(40)  评论(0编辑  收藏  举报  
点击右上角即可分享
微信分享提示