python统计HUAWEI交换机的MAC信息

import re
from netmiko import ConnectHandler
import time
import queue
import pandas as pd
import threading

date = time.strftime('%Y%m%d', time.localtime())
pattern = re.compile(r'(?P<mac>[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4})\s+(?P<vlanid>[0-9]+).*\s+(?P<interface>[XGE][a-zA-Z]+.*[0-9])')
devsres = queue.Queue()

def conn_dev(ip):
    while not ip.empty():
        net_dev = {
            'device_type': 'huawei_telnet',
            'ip': ip.get(),
            'username': 'admin',
            'password': 'admin',
            'port': '23'
        }

        telnet_client = ConnectHandler(**net_dev)
        hostname = telnet_client.find_prompt()[:-1]
        hostname = hostname.lstrip(hostname[0])
        print(hostname)

        huawei_mac = telnet_client.send_multiline(['screen-length 0 temporary', 'dis mac-address '])
        output = pattern.finditer(huawei_mac)
        maclist = []
        for i in output:
            resdict={}
            # print(i.groupdict())
            resdict['hostname']=hostname
            resdict['mac']=i.groupdict().get('mac')
            resdict['vlanid'] = i.groupdict().get('vlanid')
            resdict['interface'] = i.groupdict().get('interface')
            maclist.append(resdict)
        telnet_client.disconnect()
        devsres.put(maclist)

# res = pd.DataFrame(maclist, columns=['mac', 'vlanid', 'interface'])
# res.to_excel('%s.xlsx' % hostname)
if __name__ == "__main__":
    devs_q = queue.Queue()
    with open(r'C:\PycharmProjects\untitled1\device_ip', 'r', encoding='utf-8') as f:
        for dev in f.readlines():
            devs_q.put(dev)
    ts = []
    max_conn = 2
    for i in range(max_conn):
        t = threading.Thread(target=conn_dev, args=(devs_q,))
        t.start()
        ts.append(t)
    for t in ts:
        t.join()
    print(devsres.qsize())
    with pd.ExcelWriter('adsfsaf.xlsx') as f:
        while not devsres.empty():
            resalist=devsres.get()
            hostnamedev=resalist[0].get('hostname')
            pdres=pd.DataFrame(resalist,columns=['mac','vlanid','interface'])
            pdres.to_excel(f,sheet_name=hostnamedev)

 

posted @ 2024-05-30 17:37  Me-lihu  阅读(12)  评论(0编辑  收藏  举报