@@ -11,15 +11,28 @@ def connect_to_netbox(url, token):
11
11
12
12
Returns:
13
13
- netbox (pynetbox.core.api.Api): The Netbox API object configured to use the provided URL and token.
14
+
15
+ Raises:
16
+ - Exception: If the connection to Netbox fails.
14
17
"""
15
18
# Create a custom requests session with SSL verification disabled
16
19
session = requests .Session ()
17
20
session .verify = False # Disabling SSL verification for the session
18
21
19
- # Create a Netbox API object without specifying any session
20
- netbox = pynetbox . api ( url , token )
21
-
22
- # Set the custom session for the Netbox API object's requests session
23
- netbox . http_session = session
22
+ # Test the connection by making a direct request to /api/status/
23
+ try :
24
+ headers = { "Authorization" : f"Token { token } " }
25
+ response = session . get ( f" { url } /api/status/" , headers = headers )
26
+ response . raise_for_status () # Raise an error for HTTP status codes 4xx/5xx
24
27
25
- return netbox
28
+ # Check if the response contains the "netbox-version" key
29
+ status_data = response .json ()
30
+ if "netbox-version" in status_data :
31
+ # Create and return the Netbox API object
32
+ netbox = pynetbox .api (url , token )
33
+ netbox .http_session = session
34
+ return netbox
35
+ else :
36
+ raise Exception ("Unexpected response from Netbox /api/status/ endpoint." )
37
+ except Exception as e :
38
+ raise Exception (f"Failed to connect to Netbox: { e } " )
0 commit comments