1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
| ''' 全局设置和共用函数 ''' import os from datetime import datetime from functools import wraps import ipaddress from openpyxl import load_workbook from multiprocessing.pool import ThreadPool from netmiko import ConnectHandler, NetMikoAuthenticationException, NetMikoTimeoutException, ssh_exception
BASE_PATH = os.path.dirname((__file__))
EXPORT_PATH = os.path.join(BASE_PATH, 'EXPORT')
dir_name = datetime.now().strftime("%Y%m%d")
new_path = os.path.join(EXPORT_PATH, dir_name) if not os.path.isdir(new_path): os.makedirs(new_path)
backup_path = os.path.normpath( os.path.join(EXPORT_PATH, dir_name, 'config_backup')) config_path = os.path.normpath( os.path.join(EXPORT_PATH, dir_name, 'config_add'))
if not os.path.isdir(backup_path): os.makedirs(backup_path) if not os.path.isdir(config_path): os.makedirs(config_path)
device_file = "dev_data.xlsx"
t_pool = ThreadPool(66)
sucessful_list = [] failed_list = []
def login_start(): pass
def load_excel(): try: wb = load_workbook(device_file) return wb except FileNotFoundError: print("{} excel文件不存在".format(device_file)) except Exception: print("载入读取{} excel文件失败".format(device_file))
def get_device_info(task_name): try: wb = load_excel() ws1 = wb[wb.sheetnames[0]] for row in ws1.iter_rows(min_row=2, max_col=9): if row[2].value: if str(row[1].value).strip() == '#': continue info_dict = { 'ip': row[2].value, 'username': row[5].value, 'password': row[6].value, 'protocol': row[3].value, 'port': row[4].value, 'secret': row[7].value, 'device_type': row[8].value, 'cmd_list': get_cmd_info(task_name, wb[row[8].value.strip().lower()]), } yield info_dict else: break except Exception as e: print("get_device_info failed: {}".format(e)) finally: wb.close()
def get_cmd_info(task_name, sheet_name): cmd_list = [] try: for row in sheet_name.iter_rows(min_row=2, max_col=3): if str(row[0].value).strip() != '#' and row[1].value and task_name == 'backup_config.py': cmd_list.append(row[1].value.strip()) elif str(row[0].value).strip() != '#' and row[2].value and task_name == 'add_config.py': cmd_list.append(row[2].value.strip()) return cmd_list except Exception as e: print("get_cmd_info Error: ", e)
def get_undifined_device_info(): try: wb = load_excel() ws1 = wb[wb.sheetnames[5]] row_number = 2 for row in ws1.iter_rows(min_row=2, max_col=9): undifined_cmd_info = [] for cols in ws1.iter_cols(min_col=10, min_row=row_number, max_row=row_number, values_only=True): for col in cols: if col is None: continue undifined_cmd_info.append(col) row_number += 1
if row[2].value: if str(row[1].value).strip() == '#': continue info_dict = { 'ip': row[2].value, 'username': row[5].value, 'password': row[6].value, 'protocol': row[3].value, 'port': row[4].value, 'secret': row[7].value, 'device_type': row[8].value, 'cmd_list': undifined_cmd_info, } yield info_dict else: break except Exception as e: print("get_device_info failed: {}".format(e)) finally: wb.close()
def connect_handler(host): try: connect = '' if host['protocol'].lower().strip() == 'ssh': host['port'] = host['port'] if (host['port'] not in [22, None]) else 22 host.pop('protocol'), host.pop('cmd_list')
if 'huawei' in host['device_type']: host.pop('secret') connect = ConnectHandler(**host, conn_timeout=10) elif 'hp_comware' in host['device_type']: host.pop('secret') connect = ConnectHandler(**host) else: connect = ConnectHandler(**host, conn_timeout=10) elif host['protocol'].lower().strip() == 'telnet': host['port'] = host['port'] if (host['port'] not in [23, None]) else 23 host.pop('protocol'), host.pop('secret'), host.pop('cmd_list') host['device_type'] = host['device_type'] + '_telnet' connect = ConnectHandler(**host, fast_cli=False) else: res = "暂不支持IP地址为{}_的设备使用{}协议登陆".format(host['ip'], host['protocol']) raise ValueError(res) return True, connect
except NetMikoTimeoutException: res = "{} Can not connect to Device!".format(host['ip']) print(res) return False, res except NetMikoAuthenticationException: res = "{} username/password wrong!".format(host['ip']) print(res) return False, res except ssh_exception: res = "{} SSH parameter problem!".format(host['ip']) print(res) return False, res except Exception as e: print("{} Failed: {}".format(host['ip'], e)) return False, res
def timer(func):
@wraps(func) def wrapper(*args, **kwargs): start_time = datetime.now() func(*args, **kwargs) end_time = datetime.now() print('执行完毕,共耗时 {:0.2f} 秒.'.format((end_time - start_time).total_seconds())) print('-' * 42)
return wrapper
def result_count(func):
@wraps(func) def wrapper(*args, **kwargs): task_name, sucessful_list, failed_list = func(*args, **kwargs) result_count = ('设备总数 {} 台,成功 {} 台,失败 {} 台.'.format( len(sucessful_list) + len(failed_list), len(sucessful_list), len(failed_list))) print('\n' + '-' * 42) print(result_count) result_path = os.path.normpath(os.path.join(EXPORT_PATH, dir_name, f'result_{dir_name}.log')) print(f'\n运行结果保存路径: \"{result_path}\"\n')
return task_name, sucessful_list, failed_list
return wrapper
def write_to_file(task_name, output_filename, output): if task_name == 'backup_config.py': with open(os.path.join(backup_path, output_filename), 'a', encoding="utf-8") as f: f.write(output) elif task_name == 'add_config.py': with open(os.path.join(config_path, output_filename), 'a', encoding="utf-8") as f: f.write(output) elif task_name == 'undifined.py': with open(os.path.join(config_path, output_filename), 'a', encoding="utf-8") as f: f.write(output) else: pass
def result_write(func):
@wraps(func) def wrapper(*args, **kwargs):
task_name, sucessful_list, failed_list = func(*args, **kwargs) result_count = ('设备总数 {} 台,成功 {} 台,失败 {} 台.'.format( len(sucessful_list) + len(failed_list), len(sucessful_list), len(failed_list)))
time_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
result_path = os.path.normpath( os.path.join(EXPORT_PATH, dir_name, f'result_{dir_name}.log'))
with open(result_path, 'a', encoding="utf-8") as f: log_title = task_name.center(100, '=') + '\n' + time_str.center(100, '=') + '\n' f.write(log_title) f.write(result_count + '\n') f.write('\n执行成功设备列表:\n') for i in sucessful_list: f.write(i) f.write('\n')
f.write('\nNG设备列表:\n') for i in failed_list: f.write(i) f.write('\n') f.write('\n')
return task_name, sucessful_list, failed_list
return wrapper
def is_valid_ipv4_input(ipv4_str):
try: ipaddress.IPv4Address(ipv4_str) return True except ValueError: return False
|