смотри, есть код, в проверку if iptodelete: нужно интегрировать еще наличие…
- User
User: смотри, есть код, в проверку if ip_to_delete: нужно интегрировать еще наличие дубликатов ip, актуальный можно проверить совпадением name из бд по conip в device[conip]['alias'], если совпадает, то оставить, а те что не совпадают удалить import requests from requests.exceptions import HTTPError import re import json import dataset import sys
db = dataset.connect('mysql://noc:Cdjkjxb561@localhost/freeports?charset=utf8mb4') table = db['freeports']
def get_api(): api_dict={ 'main': 'http://10.101.15.11:8080/api', 'url_api': { 'mo_attr': '/noc/nbi/mo_attr', }, 'auth': { 'type': '', 'head': 'Authorization', 'key': 'eyJvcmciOiJub2N0ZWNoIiwiaWQiOiI2ZTlkNDgwZWEzOGM0YzNiODY4ZDMzMzA4NDdhY2I3NyIsImgiOiJzaGEyNTYifQ==' }, 'params': { 'domain': ['Ядро (concept)', 'Агрегация (concept)', 'ЦОД (concept)'], 'limit': 2000 }, 'cont_type': { 'json': 'application/json' }, 'usr_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.41' } start = 0 device = {} for j in api_dict['params']['domain']: while True: request = { 'url': api_dict['main']+api_dict['url_api']['mo_attr'], 'headers':{ "User-Agent": api_dict['usr_agent'], "Content-type": api_dict['cont_type']['json'], api_dict['auth']['head']: api_dict['auth']['key'] }, 'params': { 'administrative_domain': j, 'limit': str(api_dict['params']['limit']), 'start': start } } try: response = requests.get( request['url'], params=request['params'], headers=request['headers']) if response is not None: response.raise_for_status() response=response.json()['data'] except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') except Exception as err: print(f'Other error occurred: {err}') else: if response is None: print ('Response is None') else: for i in response: device[i['address']] = { 'id': i['id'], 'alias': i['name'], 'domain': i['administrative_domain'], 'segment': i['segment'], 'adm_dom': i['auth_profile'], 'devprofile': i['platform'], 'vers': i['version'], 'vrf': i['vrf'] } finally: if len(response) < api_dict['params']['limit']: break else: start += api_dict['params']['limit'] return device
def get_device (): device = get_api() #inc_platforms = ['S9312', # '7750 SR-12', # '7750 SR-7', # 'S6330-H48X6C', # 'S9306', # #'WS-C3750G-24TS-1U', # 'S6320-54C-EI-48S-DC', # 'S5332-H24S6Q', # 'S6348-EI', # 'S6320-50L-HI-48S', # 'S6320-54C-EI-48S-AC', # #'ME60-X8', # 'S5320-36C-EI-28S-AC', # 'S9312E', # #'NE40E-X8A', # 'DGS-3627G', # '8912', # #'X670-48x', # 'S6324-EI', # 'S5328C-EI-24S' # ] ex_platforms = [ 'WS-C3750G-24TS-1U', 'ME60-X8', 'NE40E-X8A', 'DGS-3627G', 'X670-48x', ] inc_alias = ('bsr|csw|asw|dcsw|dc-leaf') ex_ip = ('(172.\d{,3}.\d{,3}.\d{,3}|192.168.\d{,3}.\d{,3})') ex_domain = ['Интерзет'] ex_segment = ['Санкт-Петербург (InterZet) (concept)', 'Санкт-Петербург(Вестколл) (concept)'] existing_devices = {(row['name'], row['conip']) for row in table.all()} new_records = [] for i in device: if re.search(ex_ip, i) is None and device[i]['adm_dom'] not in ex_domain and re.search(inc_alias, device[i]['alias']) and device[i]['segment'] not in ex_segment and device[i]['devprofile'] not in ex_platforms: city_re = re.search('^[А-я-]+', device[i]['segment']) city_re = city_re.group() if (device[i]['alias'], i) not in existing_devices: print(f"Устройство {device[i]['alias']} с адресом {i} добавил {city_re}" ) new_records.append({'name': device[i]['alias'], 'conip': i, 'city': city_re}) else: print(f"Устройство {device[i]['alias']} с адресом {i} городом {city_re} уже есть в базе, пропускаю.") if new_records: print(f"Добавление {len(new_records)} новых записей в базу данных...") table.insert_many(new_records) all_db_ip = [db_ip['conip'] for db_ip in table.distinct('conip')] ip_to_delete = [ip for ip in all_db_ip if ip not in device] if ip_to_delete: if "-reindex" in sys.argv: print(f"Удаление {len(ip_to_delete)} устройств из базы данных...") table.delete(conip=ip_to_delete) else: print(f"В NOC отсутствуют {len(ip_to_delete)} устройств, для удаления необходимо запустить скрипт с аргументом -reindex")
- Assistant