首页 > 其他分享 >netmiko批量操作网络设备_pandas版

netmiko批量操作网络设备_pandas版

时间:2023-01-15 14:23:18浏览次数:47  
标签:info name netmiko ip self dev 网络设备 pandas mult

from concurrent.futures import ThreadPoolExecutor
import netmiko
import os
from threading import Lock
import pandas as pd

class net_dev():

    def __init__(self,excel_name):
        try :
            os.mkdir("./log")
        except:
            pass
        self.excel_name = excel_name
        self.list = [] # 空列表存储设备信息数据
        self.pool = ThreadPoolExecutor(10) # 初始化线程数量
        self.lock = Lock()  # 添加线程锁,避免写入数据丢失
        self.path = ("./log")  # 创建保存log路径
        self.mult_config=[] # 创建列表,保存多条命令。用于批量执行命令

    def get_dev_info(self):
        # 获取sheet(设备信息)的dataframe.
        df = pd.read_excel(self.excel_name,sheet_name="设备信息")
        self.list = df.to_dict(orient="records")  # 将数据打印出来,已字典存储的列表数据
        #mult_conf = df["mult_command"].values.tolist()  # 取一列的值生成列表
        print(self.list)

        # 获取sheet(CMD)的dataframe
        df1 = pd.read_excel(self.excel_name,sheet_name="CMD")
        result1 = df1.to_dict(orient="list")  # 将数据打印出来,将一列的数据存为一个字典
        self.mult_config = result1["mult_command"]
        print(self.mult_config)

    def mult_cmd_in(self,ip,user,dev_type,passwd):
        try:
            devices = {
                'device_type': dev_type,  # 锐捷os:ruijie_os, 华三:hp_comware 中兴:zte_zxros
                'ip': ip,
                'username': user,
                'password': passwd,
            }

            connect_dev = netmiko.ConnectHandler(**devices)
            cmd_out = connect_dev.send_config_set(self.mult_config,enter_config_mode=False)
            with open (ip + ".txt", "w",encoding="utf-8")  as tmp_fle:
                tmp_fle.write(cmd_out)
            print(ip + " 执行成功")

        except netmiko.exceptions.NetmikoAuthenticationException:
            self.lock.acquire()
            with open("登录失败列表", "a", encoding="utf-8") as failed_ip:
                failed_ip.write(ip + "  用户名密码错误\n")
                print(ip + " 用户名密码错误")
            self.lock.release()
        except netmiko.exceptions.NetmikoTimeoutException:
            self.lock.acquire()
            with open("登录失败列表", "a", encoding="utf-8") as failed_ip:
                failed_ip.write(ip + "       登录超时\n")
                print(ip + " 登录超时")
            self.lock.release()

    def main(self):
        for dev_info in self.list:
            #print(dev_info)
            ip = dev_info["ip"]
            #print(ip)
            user = dev_info["user"]
            dev_type = dev_info["dev_type"]
            passwd = dev_info["password"]
            self.pool.submit(self.mult_cmd_in,ip,user,dev_type,passwd)
        os.chdir(self.path)
        self.pool.shutdown(True)

yc_use = net_dev("设备信息表.xlsx")
yc_use.get_dev_info()
yc_use.main()

 

标签:info,name,netmiko,ip,self,dev,网络设备,pandas,mult
From: https://www.cnblogs.com/yc-tec/p/17053420.html

相关文章

  • pandas_notes
    set_indexvsreset_indexset_index:原本无标签索引,现设置标签索引reset_index:原本有标签索引,现重设标签索引importpandasaspddf1=pd.read_csv('internet_company_s......
  • b站pandas编程练习100例
     题1使用List构造Series使用pandas,把下方数据List,变为一个Series。将Series输出到命令行。courses=['语文','数学','英语','计算机']题解:import......
  • pandas——pandas的数据结构与创建数据对象
    1.pandas的数据结构Seriesseries是一维数据importpandasaspds=pd.Series([1,2,3,4,5])print(s.index)#获取series的索引print(s.values)#获取series的值D......
  • Requests+Etree+BeautifulSoup+Pandas+Path+Pyinstaller应用 | 获取页面指定区域数据
    (Requests+Etree+BeautifulSoup+Pandas+Path应用|获取页面指定区域数据存入html、excel文档)1需求来源获取网页指定区域数据,并进行保存;简单说就是pachong的需求了。......
  • Python:Pandas中df.iloc和df.loc区别
    df.iloc官方文档中定义为“基于整数位置的索引,用于按位置选择。”df.iloc就是只根据行列号对数据进行切片或选择。df.iloc[raw,col]:第一个参数raw表示行选,第二个参......
  • 【Python】pandas 读取,保存数据
    pandas读取/保存数据importpandasaspdfile=r''df=pd.read_excel(file)df_columns=df.columns.to_list()#字段名listredundant_column=['name','age......
  • (数据科学学习手札148)geopandas直接支持gdb文件写出与追加
    本文示例代码已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes1简介大家好我是费老师,在我之前的某篇文章中为大家介绍过如何在windows......
  • pandas库对数据的读取
    常用的数据编码格式utf-8、gbk、gb18030、gbk2312引入模块importpandasaspd读取.csv文件代码结构pd.read_csv(filepath_or_buffer,sep=’,’,header=’infer......
  • pandas库中dataframe数据结构的常用方法
    文章初衷本文与文章pandas库中series数据结构的常用方法的总结初衷相同,即将dataframe的数据结构和常用方法提供给包括笔者在内的广大读者,以便大家快捷地使用和参考。dataf......
  • pandas库中series数据结构的常用方法
    文章初衷series,又称序列。是pandas库中的一种常用数据结构。为了提高工作效率,笔者总结了该数据结构的一些常用使用方法,尽量使读者只需看本篇文章即可无障碍掌握这个叫seri......