forked from d3vi1/netbox-mcp-rw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetbox_client.py
More file actions
344 lines (277 loc) · 11.8 KB
/
netbox_client.py
File metadata and controls
344 lines (277 loc) · 11.8 KB
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
#!/usr/bin/env python3
"""
NetBox Client Library
This module provides a base class for NetBox client implementations and a REST API implementation.
"""
import abc
from typing import Any, Dict, List, Optional, Union
import requests
class NetBoxClientBase(abc.ABC):
"""
Abstract base class for NetBox client implementations.
This class defines the interface for CRUD operations that can be implemented
either via the REST API or directly via the ORM in a NetBox plugin.
"""
@abc.abstractmethod
def get(self, endpoint: str, id: Optional[int] = None, params: Optional[Dict[str, Any]] = None) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
"""
Retrieve one or more objects from NetBox.
Args:
endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
id: Optional ID to retrieve a specific object
params: Optional query parameters for filtering
Returns:
Either a single object dict or a list of object dicts
"""
pass
@abc.abstractmethod
def create(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
"""
Create a new object in NetBox.
Args:
endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
data: Object data to create
Returns:
The created object as a dict
"""
pass
@abc.abstractmethod
def update(self, endpoint: str, id: int, data: Dict[str, Any]) -> Dict[str, Any]:
"""
Update an existing object in NetBox.
Args:
endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
id: ID of the object to update
data: Object data to update
Returns:
The updated object as a dict
"""
pass
@abc.abstractmethod
def delete(self, endpoint: str, id: int) -> bool:
"""
Delete an object from NetBox.
Args:
endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
id: ID of the object to delete
Returns:
True if deletion was successful, False otherwise
"""
pass
@abc.abstractmethod
def bulk_create(self, endpoint: str, data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Create multiple objects in NetBox.
Args:
endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
data: List of object data to create
Returns:
List of created objects as dicts
"""
pass
@abc.abstractmethod
def bulk_update(self, endpoint: str, data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Update multiple objects in NetBox.
Args:
endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
data: List of object data to update (must include ID)
Returns:
List of updated objects as dicts
"""
pass
@abc.abstractmethod
def bulk_delete(self, endpoint: str, ids: List[int]) -> bool:
"""
Delete multiple objects from NetBox.
Args:
endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
ids: List of IDs to delete
Returns:
True if deletion was successful, False otherwise
"""
pass
class NetBoxRestClient(NetBoxClientBase):
"""
NetBox client implementation using the REST API.
"""
# # Example of how to use the client
# client = NetBoxRestClient(
# url="https://netbox.example.com",
# token="your_api_token_here",
# verify_ssl=True
# )
# # Get all sites
# sites = client.get("dcim/sites")
# print(f"Found {len(sites)} sites")
# # Get a specific site
# site = client.get("dcim/sites", id=1)
# print(f"Site name: {site.get('name')}")
# # Create a new site
# new_site = client.create("dcim/sites", {
# "name": "New Site",
# "slug": "new-site",
# "status": "active"
# })
# print(f"Created site: {new_site.get('name')} (ID: {new_site.get('id')})")
def __init__(self, url: str, token: str, verify_ssl: bool = True):
"""
Initialize the REST API client.
Args:
url: The base URL of the NetBox instance (e.g., 'https://netbox.example.com')
token: API token for authentication
verify_ssl: Whether to verify SSL certificates
"""
self.base_url = url.rstrip('/')
self.api_url = f"{self.base_url}/api"
self.token = token
self.verify_ssl = verify_ssl
self.session = requests.Session()
# NetBox v4 supports both legacy "Token <token>" (v1) and v2 bearer tokens.
# For v2 tokens, the full Authorization header value looks like:
# "Bearer nbx_<key>.<secret>"
# Keep compatibility by accepting either a raw token (we'll prefix with "Token ")
# or a full header value (already prefixed with "Token " or "Bearer ").
auth_value = token.strip()
if not (auth_value.startswith('Token ') or auth_value.startswith('Bearer ')):
# Heuristic: NetBox v2 API tokens start with "nbx_" and must use Bearer auth.
# https://netboxlabs.com/docs/netbox/en/stable/administration/authentication/#api-tokens
if auth_value.startswith('nbx_'):
auth_value = f'Bearer {auth_value}'
else:
auth_value = f'Token {auth_value}'
self.session.headers.update({
'Authorization': auth_value,
'Content-Type': 'application/json',
'Accept': 'application/json',
})
def _build_url(self, endpoint: str, id: Optional[int] = None) -> str:
"""Build the full URL for an API request."""
endpoint = endpoint.strip('/')
if id is not None:
return f"{self.api_url}/{endpoint}/{id}/"
return f"{self.api_url}/{endpoint}/"
def get(self, endpoint: str, id: Optional[int] = None, params: Optional[Dict[str, Any]] = None) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
"""
Retrieve one or more objects from NetBox via the REST API.
Args:
endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
id: Optional ID to retrieve a specific object
params: Optional query parameters for filtering
Returns:
Either a single object dict or a list of object dicts
Raises:
requests.HTTPError: If the request fails
"""
url = self._build_url(endpoint, id)
response = self.session.get(url, params=params, verify=self.verify_ssl)
response.raise_for_status()
data = response.json()
if id is None and 'results' in data:
# Handle paginated results
return data['results']
return data
def create(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
"""
Create a new object in NetBox via the REST API.
Args:
endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
data: Object data to create
Returns:
The created object as a dict
Raises:
requests.HTTPError: If the request fails
"""
url = self._build_url(endpoint)
response = self.session.post(url, json=data, verify=self.verify_ssl)
response.raise_for_status()
return response.json()
def update(self, endpoint: str, id: int, data: Dict[str, Any]) -> Dict[str, Any]:
"""
Update an existing object in NetBox via the REST API.
Args:
endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
id: ID of the object to update
data: Object data to update
Returns:
The updated object as a dict
Raises:
requests.HTTPError: If the request fails
"""
url = self._build_url(endpoint, id)
response = self.session.patch(url, json=data, verify=self.verify_ssl)
response.raise_for_status()
return response.json()
def delete(self, endpoint: str, id: int) -> bool:
"""
Delete an object from NetBox via the REST API.
Args:
endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
id: ID of the object to delete
Returns:
True if deletion was successful, False otherwise
Raises:
requests.HTTPError: If the request fails
"""
url = self._build_url(endpoint, id)
response = self.session.delete(url, verify=self.verify_ssl)
response.raise_for_status()
return response.status_code == 204
def bulk_create(self, endpoint: str, data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Create multiple objects in NetBox via the REST API.
Args:
endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
data: List of object data to create
Returns:
List of created objects as dicts
Raises:
requests.HTTPError: If the request fails
"""
# NetBox 3.x exposes /bulk/ endpoints; NetBox 4.x uses list payloads on
# the base endpoint for bulk operations. Try /bulk/ first for backward
# compatibility, then fall back if the server rejects it.
bulk_url = f"{self._build_url(endpoint)}bulk/"
response = self.session.post(bulk_url, json=data, verify=self.verify_ssl)
if response.status_code in (404, 405):
base_url = self._build_url(endpoint)
response = self.session.post(base_url, json=data, verify=self.verify_ssl)
response.raise_for_status()
return response.json()
def bulk_update(self, endpoint: str, data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Update multiple objects in NetBox via the REST API.
Args:
endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
data: List of object data to update (must include ID)
Returns:
List of updated objects as dicts
Raises:
requests.HTTPError: If the request fails
"""
bulk_url = f"{self._build_url(endpoint)}bulk/"
response = self.session.patch(bulk_url, json=data, verify=self.verify_ssl)
if response.status_code in (404, 405):
base_url = self._build_url(endpoint)
response = self.session.patch(base_url, json=data, verify=self.verify_ssl)
response.raise_for_status()
return response.json()
def bulk_delete(self, endpoint: str, ids: List[int]) -> bool:
"""
Delete multiple objects from NetBox via the REST API.
Args:
endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
ids: List of IDs to delete
Returns:
True if deletion was successful, False otherwise
Raises:
requests.HTTPError: If the request fails
"""
payload = [{"id": id} for id in ids]
bulk_url = f"{self._build_url(endpoint)}bulk/"
response = self.session.delete(bulk_url, json=payload, verify=self.verify_ssl)
if response.status_code in (404, 405):
base_url = self._build_url(endpoint)
response = self.session.delete(base_url, json=payload, verify=self.verify_ssl)
response.raise_for_status()
return response.status_code == 204