• Python批量备份交换机配置+自动巡检


    自动巡检功能考虑到不同设备回显有所不同,需要大量正则匹配,暂时没时间搞这些,所以索性将命令回显全部显示,没做进一步的回显提取。
    以下是程序运行示例:
    #自动备份配置:

    备份完成后,将配置保存于程序目录下的conf_bak文件夹下,如图所示:

     #自动巡检交换机设备:

    使用前需创建excel文档,写入设备登录信息,格式如下:

    本人编码能力一般,勿喷,源码: 

    1. # coding=utf-8
    2. from netmiko import ConnectHandler
    3. from openpyxl import load_workbook
    4. import os
    5. from sys import exit
    6. from netmiko import exceptions
    7. import re
    8. # 读取excel内设备列表信息
    9. def check_and_get_dev_list(filename, sheet_name):
    10. excel_information = []
    11. sheet_header = []
    12. wb = load_workbook(filename)
    13. sh = wb[sheet_name]
    14. # 获取最大行数
    15. row = sh.max_row
    16. # 获取最大列数
    17. column = sh.max_column
    18. data = []
    19. # 获取表头写入列表中方便调用
    20. for data_1 in range(1, column+1):
    21. get_sheet_header = sh.cell(row=1, column=data_1).value
    22. sheet_header.append(get_sheet_header)
    23. # 第一行为表头, 此处 row +1 是pyton循环时不读取最后一个数
    24. for row_1 in range(2, row + 1):
    25. # 存储一行信息
    26. sheet_data_1 = dict()
    27. # 逐行读取表中的数据
    28. for b in range(1, column + 1):
    29. cell = sh.cell(row=row_1, column=b).value
    30. # 将数据已字典形式写入 sheet_data_1 中
    31. # if cell != None:
    32. sheet_data_1[sheet_header[b-1]] = cell
    33. excel_information.append(sheet_data_1)
    34. for i in excel_information:
    35. if i['ip'] != None:
    36. data.append(i)
    37. return data
    38. #获取excel数据并整合成dev字典
    39. def get_dev():
    40. res = check_and_get_dev_list('./resource.xlsx', 'Sheet1')
    41. devices = []
    42. for i in res:
    43. if i['protocol'] == 'telnet':
    44. i['type'] = i['type']+'_telnet'
    45. dev = {'device_type':i['type'],
    46. 'host': i['ip'],
    47. 'username': i['username'],
    48. 'password': i['password'],
    49. 'secret': i['enpassword'],
    50. 'port': i['port'],}
    51. devices.append(dev)
    52. return devices
    53. # 配置批量备份导出
    54. def devices_confbak(devices=''):
    55. # 创建备份文件夹
    56. try:
    57. path = './conf_bak'
    58. os.makedirs(path)
    59. except FileExistsError:
    60. pass
    61. # 存储连接失败的IP
    62. failed_ips = []
    63. # 循环登录设备获取配置
    64. for dev in devices:
    65. try:
    66. with ConnectHandler(**dev) as conn:
    67. print('\n----------成功登录到:' + dev['host'] + '----------')
    68. conn.enable()
    69. if 'cisco_ios' in dev['device_type']:
    70. output = conn.send_command(command_string='show run')
    71. elif 'huawei' or 'hp_comware' in dev['device_type']:
    72. output = conn.send_command(command_string='dis current-configuration')
    73. else:
    74. print('error')
    75. with open('./conf_bak/'+ dev['host'] +'_conf_bak.txt', mode='w', encoding='utf8') as f:
    76. print('正在备份:'+dev['host'])
    77. # 文件读写异常处理
    78. try:
    79. f.write(output)
    80. except PermissionError:
    81. print('*****-无写入权限,请将文件夹赋予读写权限-*****')
    82. continue
    83. else:
    84. print('备份成功!')
    85. # 连接异常处理
    86. except exceptions.NetmikoAuthenticationException:
    87. print('\n**********'+dev['host']+':登录验证失败!**********')
    88. failed_ips.append(dev['host'])
    89. continue
    90. except exceptions.NetmikoTimeoutException:
    91. print('\n**********'+dev['host']+':目标不可达!**********')
    92. failed_ips.append(dev['host'])
    93. continue
    94. except exceptions.ReadTimeout:
    95. print('\n**********'+dev['host']+':读取超时,请检查enable密码是否正确!**********')
    96. failed_ips.append(dev['host'])
    97. continue
    98. if len(failed_ips) > 0:
    99. print('\n以下设备连接失败,请检查:')
    100. for x in failed_ips:
    101. print(x)
    102. return 1
    103. # 配置巡检
    104. def devices_autocheck(devices='', cmd=''):
    105. # 存储命令执行回显
    106. results = []
    107. try:
    108. for x in range(len(devices)):
    109. # 循环登录设备
    110. with ConnectHandler(**devices[x]) as conn:
    111. conn.enable()
    112. print('正在巡检:'+devices[x]['host']+' ...')
    113. result = [devices[x]['host'],devices[x]['device_type']]
    114. for i in range(len(cmd)):
    115. # 循环执行命令,根据不同设备执行不同命令
    116. if 'cisco_ios' in devices[x]['device_type']:
    117. output = conn.send_command(command_string=str(cmd[i]['cisco']))
    118. elif 'huawei' or 'hp_comware' in devices[x]['device_type']:
    119. conn.send_command(command_string='sys',expect_string=']')
    120. output = conn.send_command(command_string=str(cmd[i]['huawei']))
    121. result.append(output)
    122. results.append(result)
    123. except exceptions.NetmikoAuthenticationException:
    124. print('\n**********'+devices[x]['host']+':登录验证失败!**********')
    125. except exceptions.NetmikoTimeoutException:
    126. print('\n**********' + devices[x]['host'] + ':目标不可达!**********')
    127. except exceptions.ReadTimeout:
    128. print('\n**********' + devices[x]['host'] + ':读取超时,请检查enable密码是否正确!**********')
    129. return results
    130. # 计算内存使用率
    131. def get_mem(memstr,devtype=''):
    132. if 'cisco' in devtype:
    133. total_match = re.search(r'Processor Pool Total:\s+(\d+)', memstr)
    134. used_match = re.search(r'Used:\s+(\d+)', memstr)
    135. # 提取总数和已用数,并将其转换为整数
    136. total = int(total_match.group(1))
    137. used = int(used_match.group(1))
    138. # 计算使用百分比
    139. percentage = used / total * 100
    140. return f"{percentage:.0f}%"
    141. elif 'huawei' in devtype:
    142. match = re.search(r"Memory Using Percentage Is:\s*(\d+)%", memstr)
    143. if match:
    144. memory_percentage = match.group(1)
    145. return memory_percentage+'%'
    146. else:
    147. return "No match found."
    148. # 获取CPU利用率
    149. def get_cpu(cpustr,devtype=''):
    150. if 'cisco' in devtype:
    151. pattern = r"CPU utilization for five seconds: (\d+)%"
    152. match = re.search(pattern, cpustr)
    153. if match:
    154. cpu_utilization = match.group(1)
    155. return cpu_utilization+'%'
    156. else:
    157. return "No match found."
    158. elif 'huawei' in devtype:
    159. match = re.search(r"\b(\d+(\.\d+)?)%.*?\bMax", cpustr)
    160. if match:
    161. cpu_utilization = match.group(1)
    162. return cpu_utilization+'%'
    163. else:
    164. return "No match found."
    165. # 运行主程序
    166. if __name__ == '__main__':
    167. while True:
    168. print("\n##############################################\n")
    169. print("1:批量备份交换机配置")
    170. print("2:批量巡检交换机设备")
    171. print("0:退出")
    172. option = str(input("请输入需要的操作编号:"))
    173. if option == '1':
    174. dev = get_dev()
    175. devices_confbak(devices=dev)
    176. continue
    177. elif option == '2':
    178. # 定义巡检命令
    179. # cmds[x]['cisco']
    180. # cmds[x]['huawei']
    181. cmds = [
    182. {'cisco':'show clock','huawei':'display clock'}, #检查时钟
    183. {'cisco':'show env power','huawei':'display power'}, #检查电源
    184. {'cisco':'show env fan','huawei':'display fan'}, #检查风扇
    185. {'cisco':'show env temperature status', 'huawei': 'display environment'},#检查温度
    186. {'cisco':'show processes cpu', 'huawei': 'display cpu-usage'}, #检查CPU利用率
    187. {'cisco':'show processes memory', 'huawei': 'display memory-usage'}, #检查内存利用率
    188. ]
    189. dev = get_dev()
    190. checkres = devices_autocheck(dev,cmds)
    191. for res in checkres:
    192. # print(res)
    193. print('\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
    194. print(res[0]+'-巡检结果:')
    195. print('\n时钟:\n'+res[2])
    196. print('电源:\n'+res[3])
    197. print('风扇:\n'+res[4])
    198. if 'Unrecognized command' in res[5]:
    199. print('温度:\n该设备不支持获取此数据!')
    200. else:print('温度:\n'+res[5])
    201. print('CPU利用率:\n' + get_cpu(res[6],res[1]))
    202. print('内存利用率:\n' + get_mem(res[7],res[1]))
    203. print('\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
    204. continue
    205. elif option == '0':
    206. break
    207. else:
    208. print("请输入正确的编号!")

  • 相关阅读:
    【Docker系列】从头学起 Docker——docker run 命令详解
    【华为机试真题详解】快速人名查找【2022 Q2 | 200分】
    数据透视表上线!如何在纯前端实现这个强大的数据分析功能?
    python数据精度问题
    backbone核心详解系列——RepVGG
    MyBatis insert标签
    【Linux】解决缓存锁问题:无法获得锁 /var/lib/dpkg/lock-frontend
    【STM32】入门(二):跑马灯-GPIO端口输出控制
    精神分裂型患者大脑结构和功能连接的改变
    Grade 5 Math
  • 原文地址:https://blog.csdn.net/leavemyleave/article/details/134366371