全网最全Python netmiko库实现自动化备份网络设备配置、路由、cpu、内存、电源等

文章目录

  • 前言
  • 一、netmiko 4.1.0版本安装
  • 二、自动化备份代码讲解
    • 1.目录结构
    • 2.完整代码详解
    • 3.netmiko支持设备
  • 三、参考资料
    • 1.Python官方netmiko库
    • 2.Github官方netmiko库
  • 三、exe脚本下载

前言

余生平,怎一个懒字了得。
小白Python自动化运维随笔(懒人专属)。
Python版本3.9.12

一、netmiko 4.1.0版本安装

进入CMD,输入下记命令进行安装

pip install  netmiko==4.1.0

查看pip安装的组件列表命令

pip list

二、自动化备份代码讲解

1.目录结构

net_config_backup:log备份存放文件夹
devlist.txt:SSH登录设备信息

PE,hp_comware,1.1.1.1,admin,password
PE,huawei,1.1.1.1,admin,password
PE,cisco_ios,1.1.1.1,admin,password

hp_comvare 代表H3C设备
huawei 代表华为设备
cisco_ios 代表思科设备

ssh.py:python代码
在这里插入图片描述

2.完整代码详解

from netmiko import ConnectHandler
import time
import os
import shutil
#python 3.9.12
#netmiko 4.1.0

#定义全局变量
Today = time.strftime( "%Y-%m-%d", time.localtime())    #获取本地时间
OsPath = os.path.abspath(".")
OsPath = OsPath.replace('\\', '/')  #获取上级目录
FilePath = OsPath
BackPath = OsPath + '/net_config_backup/'
Delimiter = '--------------------------------------------------------------------------'
#华三 华为命令列表
H3cCommandList = ['dis version','dis current-configuration','dis device',
                  'dis interface brief','dis vlan all',
                  'dis clock','dis cpu','dis memory','dis power',
                  'dis fan','dis temperature all','dis logbuffer','dis ospf brief',
                  'dis ospf peer','dis ospf lsdb','dis bgp peer v4',
                  'dis bgp routing-table v4', 'dis ip routing-table all-routes']

#浪潮 思科命令列表
InspurCommandList = ['show version','show run','show ip interface brief',
                     'show interface status','show vlan all','show clock',
                     'show clock utc','show cpu traffic-limit',
                     'show cpu traffic-statistics receive',
                     'show cpu traffic-statistics transmit','show memory',
                     'show power-info','show logging buffer ']


def make_dir(path_name):    #创建文件夹
    if os.path.exists(path_name):
        shutil.rmtree(path_name)  #删除已有文件夹
    os.mkdir(path_name)


def txt_write(logname,output,command):  #配置写入文档中
    time.sleep(1)
    wr = open(logname, 'a', encoding='utf-8')
    wr.write(command + '\n')
    wr.write(output)
    wr.write('\n' + Delimiter + '\n')
    wr.close



def ssh_session(devlist): ##定义备份函数
    list= line.split( ",")
    hostname = str( list[0])
    devtype = list[1]
    ip = list[2]
    name = list[3]
    devpasswd = list[4]
    
    if devtype == 'hp_comware' or devtype == 'huawei':     #H3C 华为设备
        net_connect = ConnectHandler(
                device_type=devtype,
                ip=ip,
                username=name,
                password=devpasswd,
            )
        for command in H3cCommandList:
            output = net_connect.send_command(command)
            logname =BackPath + Today + "/"+ hostname + "__" + ip + "__" + Today + ".log"
            txt_write(logname,output,command)
    if devtype == 'cisco_ios':      #思科 浪潮设备
        net_connect = ConnectHandler(
                device_type=devtype,
                ip=ip,
                username=name,
                password=devpasswd,
            )
        for command in InspurCommandList:
            output = net_connect.send_command(command)
            logname =BackPath + Today + "/"+ hostname + "__" + ip + "__" + Today + ".log"
            txt_write(logname,output,command)


if __name__ == '__main__':
    make_dir(BackPath + Today + "/")
    time.sleep(1)  
    devlist = open( FilePath + '/devlist.txt', 'r')
    for line in devlist.readlines():
        line = line.replace('\n', '')   #去除\N
        line = line.replace(' ', '')   #去除空格
        ssh_session(line)
    devlist.close

3.netmiko支持设备

windows系统默认存放路径及支持设备一览(AppData为文件夹隐藏的项目)

C:\Users\PC-li\AppData\Local\Programs\Python\Python39\Lib\site-packages\netmiko\ssh_dispatcher.py

# The keys of this dictionary are the supported device_types
CLASS_MAPPER_BASE = {
    "a10": A10SSH,
    "accedian": AccedianSSH,
    "adtran_os": AdtranOSSSH,
    "alcatel_aos": AlcatelAosSSH,
    "alcatel_sros": NokiaSrosSSH,
    "allied_telesis_awplus": AlliedTelesisAwplusSSH,
    "apresia_aeos": ApresiaAeosSSH,
    "arista_eos": AristaSSH,
    "aruba_os": ArubaSSH,
    "aruba_osswitch": HPProcurveSSH,
    "aruba_procurve": HPProcurveSSH,
    "avaya_ers": ExtremeErsSSH,
    "avaya_vsp": ExtremeVspSSH,
    "broadcom_icos": BroadcomIcosSSH,
    "brocade_fos": BrocadeFOSSSH,
    "brocade_fastiron": RuckusFastironSSH,
    "brocade_netiron": ExtremeNetironSSH,
    "brocade_nos": ExtremeNosSSH,
    "brocade_vdx": ExtremeNosSSH,
    "brocade_vyos": VyOSSSH,
    "checkpoint_gaia": CheckPointGaiaSSH,
    "calix_b6": CalixB6SSH,
    "cdot_cros": CdotCrosSSH,
    "centec_os": CentecOSSSH,
    "ciena_saos": CienaSaosSSH,
    "cisco_asa": CiscoAsaSSH,
    "cisco_ftd": CiscoFtdSSH,
    "cisco_ios": CiscoIosSSH,
    "cisco_nxos": CiscoNxosSSH,
    "cisco_s300": CiscoS300SSH,
    "cisco_tp": CiscoTpTcCeSSH,
    "cisco_viptela": CiscoViptelaSSH,
    "cisco_wlc": CiscoWlcSSH,
    "cisco_xe": CiscoIosSSH,
    "cisco_xr": CiscoXrSSH,
    "cloudgenix_ion": CloudGenixIonSSH,
    "coriant": CoriantSSH,
    "dell_dnos9": DellForce10SSH,
    "dell_force10": DellForce10SSH,
    "dell_os6": DellDNOS6SSH,
    "dell_os9": DellForce10SSH,
    "dell_os10": DellOS10SSH,
    "dell_sonic": DellSonicSSH,
    "dell_powerconnect": DellPowerConnectSSH,
    "dell_isilon": DellIsilonSSH,
    "dlink_ds": DlinkDSSSH,
    "endace": EndaceSSH,
    "eltex": EltexSSH,
    "eltex_esr": EltexEsrSSH,
    "enterasys": EnterasysSSH,
    "ericsson_ipos": EricssonIposSSH,
    "extreme": ExtremeExosSSH,
    "extreme_ers": ExtremeErsSSH,
    "extreme_exos": ExtremeExosSSH,
    "extreme_netiron": ExtremeNetironSSH,
    "extreme_nos": ExtremeNosSSH,
    "extreme_slx": ExtremeSlxSSH,
    "extreme_tierra": ExtremeTierraSSH,
    "extreme_vdx": ExtremeNosSSH,
    "extreme_vsp": ExtremeVspSSH,
    "extreme_wing": ExtremeWingSSH,
    "f5_ltm": F5TmshSSH,
    "f5_tmsh": F5TmshSSH,
    "f5_linux": F5LinuxSSH,
    "flexvnf": FlexvnfSSH,
    "fortinet": FortinetSSH,
    "generic": GenericSSH,
    "generic_termserver": TerminalServerSSH,
    "hp_comware": HPComwareSSH,
    "hp_procurve": HPProcurveSSH,
    "huawei": HuaweiSSH,
    "huawei_smartax": HuaweiSmartAXSSH,
    "huawei_olt": HuaweiSmartAXSSH,
    "huawei_vrpv8": HuaweiVrpv8SSH,
    "ipinfusion_ocnos": IpInfusionOcNOSSSH,
    "juniper": JuniperSSH,
    "juniper_junos": JuniperSSH,
    "juniper_screenos": JuniperScreenOsSSH,
    "keymile": KeymileSSH,
    "keymile_nos": KeymileNOSSSH,
    "linux": LinuxSSH,
    "mikrotik_routeros": MikrotikRouterOsSSH,
    "mikrotik_switchos": MikrotikSwitchOsSSH,
    "mellanox": MellanoxMlnxosSSH,
    "mellanox_mlnxos": MellanoxMlnxosSSH,
    "mrv_lx": MrvLxSSH,
    "mrv_optiswitch": MrvOptiswitchSSH,
    "netapp_cdot": NetAppcDotSSH,
    "netgear_prosafe": NetgearProSafeSSH,
    "netscaler": NetscalerSSH,
    "nokia_sros": NokiaSrosSSH,
    "oneaccess_oneos": OneaccessOneOSSSH,
    "ovs_linux": OvsLinuxSSH,
    "paloalto_panos": PaloAltoPanosSSH,
    "pluribus": PluribusSSH,
    "quanta_mesh": QuantaMeshSSH,
    "rad_etx": RadETXSSH,
    "raisecom_roap": RaisecomRoapSSH,
    "ruckus_fastiron": RuckusFastironSSH,
    "ruijie_os": RuijieOSSSH,
    "sixwind_os": SixwindOSSSH,
    "sophos_sfos": SophosSfosSSH,
    "supermicro_smis": SmciSwitchSmisSSH,
    "tplink_jetstream": TPLinkJetStreamSSH,
    "ubiquiti_edge": UbiquitiEdgeSSH,
    "ubiquiti_edgerouter": UbiquitiEdgeRouterSSH,
    "ubiquiti_edgeswitch": UbiquitiEdgeSSH,
    "ubiquiti_unifiswitch": UbiquitiUnifiSwitchSSH,
    "vyatta_vyos": VyOSSSH,
    "vyos": VyOSSSH,
    "watchguard_fireware": WatchguardFirewareSSH,
    "zte_zxros": ZteZxrosSSH,
    "yamaha": YamahaSSH,
    "zyxel_os": ZyxelSSH,
}

三、参考资料

1.Python官方netmiko库

2.Github官方netmiko库

三、exe脚本下载

目前支持win10版本下,H3C、华为、浪潮、思科设备。
下载地址在我的博客资源里

你可能感兴趣的:(网工Python自动化编程,python,自动化,网络)