-
Notifications
You must be signed in to change notification settings - Fork 0
/
nb-load.py
212 lines (159 loc) · 6.06 KB
/
nb-load.py
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
#!/usr/bin/python3
import os
import re
import pynetbox
from ipaddress import ip_network, ip_address, IPv4Network
from dotenv import load_dotenv
from fuzzysearch import find_near_matches
from Libs.LibreNMSAPIClient.LibreNMSAPIClient import LibreNMSAPIClient
def connect_to_netbox(netbox_url=None, api_token=None):
if api_token is None and netbox_url is None:
load_dotenv()
netbox_url = os.environ['Netbox_URL']
api_token = os.environ['Netbox__APIToken']
return(pynetbox.api(url=netbox_url, token=api_token))
def cache_dicts(nb):
# Cache device types by Part Number
device_types = {}
all_types = nb.dcim.device_types.all()
for dt in all_types:
device_types[dt.part_number] = dt.id
# Cache roles
roles = {}
all_roles = nb.dcim.device_roles.all()
for role in all_roles:
roles[role.display] = role.id
# Cache sites
sites = {}
all_sites = nb.dcim.sites.all()
for site in all_sites:
sites[site.display] = site.id
return device_types, roles, sites
mapping = [
["Datacenter 1", "name", "dc1-*"],
["Datacenter 2", "name", "c2-*"],
["Datacenter 1", "location", "Verne"],
["Datacenter 2", "location", "Fortress*"],
["XXX", "ip", "172.21.42.0/24"]
]
def match_site(name, ip=None, location=None):
for site, field, pattern in mapping:
try:
regex = re.compile(pattern, re.IGNORECASE)
except re.error:
print(f"Invalid pattern {pattern}")
continue
# print(type(location), location)
if field == "ip":
try:
network = ip_network(pattern)
if isinstance(network, IPv4Network):
ip_addr = ip_address(ip)
if ip_addr in network:
return site
except ValueError:
print(f"Invalid network: {pattern}")
continue
if field == "location":
if location:
location = location.replace("|", " ")
if regex.search(location):
print(site, location)
return site
if field == "name" and regex.search(name):
print(site, name)
return site
return None
# return None
# if field == "location" and re.search(".*verne.*", "Verne", re.IGNORECASE):
# print("GAY!!")
# if field == "location" and re.search(pattern, location, re.IGNORECASE):
# return site
# if field == "name" and re.search(pattern, name):
# return site
# if field == "ip" and re.search(pattern, ip):
# return site
return None
def create_devices(nb, ldevices, device_types, roles, sites):
# print(find_closest_id('FGT_1800F', device_types))
# print(roles)
# print(sites)
for name, value in ldevices.items():
device_type_id = find_closest_id(value['device_type'], device_types, 4)
role_id = find_closest_id(value['device_role'], roles, 2)
# print(name, value["mgmt_ip"], value["location"])
site_id = match_site(name, value["mgmt_ip"], value["location"])
# print(f" {value['device_type']} -- {device_type_id}")
# print(f" {name} : {value['device_role']} -- {role_id}")
# print(f" {name} : {value['site']} -- {site_id}")
# print(f"type: {device_type_id} role: {role_id}, site: {site_id}")
# nb.dcim.devices.create(
# name=name,
# device_type=device_type_id,
# device_role=role_id,
# site=site_id,
# # other attrs
# )
# def find_closest_value(search_string, variable_names, threshold=5):
# matches = []
# for name in variable_names:
# match = find_near_matches(search_string, name, max_l_dist=1)
# if match:
# matches.append((name, match[0].dist))
# matches.sort(key=lambda x: x[1]) # Sort matches by distance
# if 0 < len(matches) < threshold:
# return matches[0][0]
# return None
def find_closest_id(search_string, lookup_dict, threshold=5):
if not search_string:
return None
search = clean_string(search_string)
matches = []
for name in lookup_dict:
lookup = clean_string(name)
match = find_near_matches(search, lookup, max_l_dist=1)
if match:
matches.append((name, match[0].dist))
matches.sort(key=lambda x: x[1]) # Sort matches by distance
if matches and (matches[0][1] == 0 or (0 < len(matches) < threshold)):
return lookup_dict[matches[0][0]]
return None
def clean_string(string):
ignore_words = ["Chassis", "Nexus"]
string = re.sub("|".join(ignore_words) , "", string, flags=re.I)
return string.replace("_", " ").replace("-", " ").replace(",", " ")
def get_normalized_librenms(lnms) -> dict:
result = {}
for device in lnms.list_devices():
name = str(device["sysName"]).split(".")[0]
name = name.casefold()
result[name] = {
"full_name": device["sysName"],
#"libre_id": device["device_id"],
"mgmt_ip": device["ip"],
"device_type": device["hardware"],
"serial": device["serial"],
"location": device["location"],
"device_role": device["type"],
}
return result
def main():
lnms = LibreNMSAPIClient()
nb = connect_to_netbox()
#nb.http_session.verify = False #if netbox has no cert
# Cache lookups
device_types, roles, sites = cache_dicts(nb)
ldevices = get_normalized_librenms(lnms)
### WORKS:
# search_term = 'S-C290X-48FPD-L'
# closest_matches = find_closest_id(search_term, device_types)
# print(closest_matches)
#TEST PRINTS
# print(ldevices)
# print(device_types)
# print(roles)
# print(sites)
# Create devices
create_devices(nb, ldevices, device_types, roles, sites)
if __name__ == "__main__":
main()