实验环境:
如图所示,SW1-SW5上分别已经配置了SSH,使用外部PC可以SSH到其中。
在本次实验中,主要使用了如下三个模块:
- openpyxl,对excel文件进行操作,具体可以参考:https://zhuanlan.zhihu.com/p/317826761
- gevent,使用协程,同时对五台设备进行操作,可以参考:https://blog.csdn.net/tushanpeipei/article/details/116612802?spm=1001.2014.3001.5501
- napalm-huawei-vrp,SSH到交换机,并提取格式化信息,可以参考:https://blog.csdn.net/tushanpeipei/article/details/117531627?spm=1001.2014.3001.5501
python代码:
from napalm import get_network_driver
from openpyxl import Workbook
from openpyxl.styles import Color, PatternFill, Font, Border, Side
import gevent
from gevent import monkey
from pprint import pprint
monkey.patch_all()
driver = get_network_driver('huawei_vrp')
devices_ip = ['192.168.0.11', '192.168.0.22', '192.168.0.33', '192.168.0.44', '192.168.0.55']
def collect_basic_info(ip, fill, border):
print("start:", ip)
try:
SW = driver(ip, 'prin', 'Huawei@123')
SW.open()
print(ip + '连接成功')
basic_info = SW.get_facts()
hostname = basic_info.get('hostname')
interfaces_ip_info = SW.get_interfaces_ip()
ws = wb.create_sheet(hostname)
ws['A1'] = 'Interfaces'
ws['B1'] = 'IP'
ws['C1'] = 'Mask'
ws['A1'].fill = fill
ws['B1'].fill = fill
ws['C1'].fill = fill
interfaces_list = []
ip_addr_list = []
mask_list = []
for key, values in interfaces_ip_info.items():
interfaces_list.append(key)
for ip, mask in values['ipv4'].items():
ip_addr_list.append(ip)
mask_list.append(mask.get('prefix_length'))
row_numbers = [n + 2 for n in range(len(interfaces_list))]
for interface, row in zip(interfaces_list, row_numbers):
ws.cell(row=row, column=1, value=interface)
for ip_addr, row in zip(ip_addr_list, row_numbers):
ws.cell(row=row, column=2, value=ip_addr)
for mask, row in zip(mask_list, row_numbers):
ws.cell(row=row, column=3, value=mask)
dims = {}
for row in ws.rows:
for cell in row:
cell.border = border
if cell.value:
dims[cell.column_letter] = max((dims.get(cell.column_letter, 0), len(str(cell.value))))
for col, value in dims.items():
ws.column_dimensions[col].width = value + 1
except Exception as e:
print(e)
print("end:", ip)
if __name__ == '__main__':
wb = Workbook()
yellowFill = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid')
thin_border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'),
bottom=Side(style='thin'))
tasks = [gevent.spawn(collect_basic_info, ip, yellowFill, thin_border) for ip in devices_ip]
all_result = gevent.joinall(tasks)
ws = wb["Sheet"]
wb.remove(ws)
print(wb.sheetnames)
wb.save('huawei_interface_ip_info.xlsx')
pycharm运行结果:
查看Excel上的最终结果:
参考资料: 网络工程师的Python之路—https://zhuanlan.zhihu.com/p/317826761
|