看了这篇文章 ,觉得很实用,于是写了一个python 版的,支持Linux 和windows 平台使用,对于Linux (arp -n ) 和windows (arp -a)导出的arp表,进行解析并输出结果。
如何使用
–oui-file 指的是 oui.txt的路径,程序默认值为当前目录下的oui.txt , 即:./oui.txt
–arp-tab-file 指的是 导出的arp表的路径
1、首先你要导出系统上的arp 表
windows > arp -a > arp.txt Linux # arp -n >arp.txt
2、 然后执行网卡厂商解析工具(这里暂为mac.py)
3、解析结果保存在当前目录下的result.txt 中
测试效果如下:
Linux:
Windows:
源码:
#!/usr/bin/env python # -*- coding:utf8 -*- """ Coded by bgusko63190 """ import re import sys import codecs import argparse def parse_oui(oui_path): """ 载入并解析oui.txt,生成'厂商标识':'厂商名称' 字典 """ oui_dict = dict() with codecs.open(oui_path, 'r', encoding='utf8') as fd: for line in fd: if '(hex)' in line: _line = line.split('(hex)') flag = _line[0].strip() manufacturers = _line[1].strip() oui_dict[flag] = manufacturers return oui_dict def parse_arp_tab(arp_tab_path, oui_path): """ :param arp_tab_path: arp -n 生生结果保存文件路径(支持windows ar -a 和Linux的arp -n 结果格式) :param oui_path: oui.txt的路径 :return: """ parse_result = [] oui_dict = parse_oui(oui_path) # 支持 00:42:5a:38:9f:56 , 00-42-5a-38-9f-56,00.42.5a.38.9f.56 3种格式的MAC地址 mac_pattern = re.compile( '([0-9a-fA-F]{1,2}[-]){5}([0-9a-fA-F]{1,2})|([0-9a-fA-F]{1,2}[:]){5}([0-9a-fA-F]{1,2})|([0-9a-fA-F]{1,2}[.]){5}([0-9a-fA-F]{1,2})', re.VERBOSE | re.IGNORECASE) result_lines = [] with codecs.open(arp_tab_path, 'r', encoding='utf8') as fd: for line in fd: _line = None if u'类型' in line: _line = line.strip() + '/t/t' + u'厂商' elif 'Type' in line or 'Iface' in line: _line = line.strip() + '/t/t' + 'manufacturers' else: try: if u'态' in line or 'dynamic' in line or 'static' in line or 'ether' in line: # _line = line.strip() + '/t/t' + oui_dict[mac_pattern.search(line).group().rsplit('-', 3)[0].upper()] manu = re.split('[-:.]', mac_pattern.search(line).group(), 3) manu_flag = manu[0] + '-' + manu[1] + '-' + manu[2] _line = line.strip() + '/t/t' + oui_dict[manu_flag.upper()] except KeyError: _line = line.strip() + '/t/t' + u'unknown' except: # print line.strip() pass if _line: result_lines.append(_line + '/n') else: # print line pass with codecs.open('result.txt', 'w', encoding='utf8') as fd: fd.writelines(result_lines) if __name__ == '__main__': reload(sys) sys.setdefaultencoding('utf8') parse = argparse.ArgumentParser() parse.add_argument('--oui-file', dest='oui', type=str, default='./oui.txt', help='oui file path') parse.add_argument('--arp-tab-file', dest='arp', type=str, required=True, help='arp tab file path') argument = parse.parse_args() parse_arp_tab(argument.arp, argument.oui)
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/55041.html