python3 思科交换机配置保存及导出

pip3 install netmiko
pip3 install openpyxl

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from netmiko import ConnectHandler
import os,time
import openpyxl


def Cisco(ip,username,password,secret):
    "交换机配置导出函数"
    cisco={
        "device_type":"cisco_ios",
        "ip":ip,
        "username":username,
        "password":password,
        "secret":secret
    }
    #print(cisco)
    #print(u'正在连接交换机:%s\n' % (ip))
    net_connect = ConnectHandler(**cisco)   #连接交换机
    net_connect.enable()                    #进入使能模式
    net_connect.send_command("wr")          #配置保存
    time.sleep(5)                           #等待配置保存
    commands = [
        #命令集合
        'show run',
        'show ip int brief',
        'show ip route',
        'show arp',
        'show mac add',
        'show version',
        'show logging'
    ]
    timestr = time.strftime('%Y-%m-%d', time.localtime(time.time()))    #记录当时年月日
    filename = u'%s_%s.txt' % (timestr,ip)                              #设置文件名格式
    path = os.path.dirname((os.path.dirname(os.path.abspath(__file__))))#记录保存路径
    file_path = os.path.join(path,file,filename)                        #记录文件保存路径(按需)
    #print(file_path)
    for cmd in commands:
        #循环执行命令集
        save = open(file_path,"a",encoding="utf-8")         #以追加方式添加
        result=net_connect.send_command(cmd)                #保存命令结果
        save.write("#%s\n" %cmd)                            #将命令写入文件
        save.write('%s\n' %result)                          #将命令结果写入文件
        save.write("\n")
    net_connect.disconnect()                                #断开连接

file = 'switch'+time.strftime('%Y-%m', time.localtime(time.time()))     #记录当前
path = os.path.dirname((os.path.dirname(os.path.abspath(__file__))))    #记录文件夹格式,按需更改
file_path = os.path.join(path, file)                        #保存文件夹格式
if not os.path.exists(file_path):                           #判断是否创建文件夹
    os.mkdir(file_path)
    #print("mkdir success")
else:
    pass
    #print("exist")


###读取文本###
f=open("soho-list","r",encoding="utf-8")
line=f.readline()
while line:
    #print(line)
    list = line.split()
    a = list[0]
    b = list[1]
    c = list[2]
    d = list[3]
    print(a,b,c,d)
    Cisco(a,b,c,d)
    line=f.readline()

###读取Excel###
# wb=openpyxl.load_workbook("password.xlsx")                  #读取excel表格
# sheet_list=wb.sheetnames                                    #获取excel表格所有sheet名称,返回列表形式
# for i in sheet_list:
#     sheet1=wb[i]
#     for row in range (1,sheet1.max_row+1):                  #循环读取单个sheet表格的每行数据
#         a = (sheet1['A%s' %row].value)
#         b = (sheet1['B%s' %row].value)
#         c = (sheet1['C%s' %row].value)
#         d = (sheet1['D%s' %row].value)
#         Cisco(a, b, c, d)
#     break                                                   #控制是否只用单个sheet

你可能感兴趣的:(python3 思科交换机配置保存及导出)