-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimport_device_by_ids.py
78 lines (67 loc) · 2.92 KB
/
import_device_by_ids.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
import pynetbox
import urllib3
import time
import pandas as pd
import csv
# Define your NetBox URL and API key
netbox_url = "enter your netbox URL"
netbox_api_key = "enter your netbox token"
# Initialize the pynetbox API instance
response = pynetbox.api(url=f"https://{netbox_url}", token=netbox_api_key)
response.http_session.verify = False
urllib3.disable_warnings()
def add_device(device_name, device_type_id, role_id, site_id, serial_number, manufacturer_id, device_status):
"""Add a device with the provided details."""
device_data = {
"name": device_name,
"device_type": device_type_id,
"role": role_id,
"site": site_id,
"serial": serial_number,
"manufacturer": manufacturer_id,
"status": device_status,
}
try:
result = response.dcim.devices.create(device_data)
print(result)
except pynetbox.RequestError as e:
error_message = f"Error creating device {device_name}: {e}"
print(error_message)
with open('error_devices.txt', 'a') as error_file:
error_file.write(f"{error_message}\n")
# Read the device details from the Excel file
excel_file = 'import_device_details.xlsx'
df = pd.read_excel(excel_file)
# Strip any leading or trailing whitespace from the column names
df.columns = df.columns.str.strip()
# Ensure all expected columns are present
expected_columns = ['device_name', 'device_type_id', 'role_id', 'site_id', 'serial_number', 'manufacturer_id', 'device_status']
missing_columns = [col for col in expected_columns if col not in df.columns]
if missing_columns:
print(f"Missing columns in the Excel file: {missing_columns}")
else:
# Handle NaN values which replaces NaN values with empty strings
df.fillna('', inplace=True)
# Iterate over each row in the DataFrame
for index, row in df.iterrows():
try:
time.sleep(0.5) # Optional delay to avoid hitting rate limits
device_name = row['device_name']
device_type_id = row['device_type_id']
role_id = row['role_id']
site_id = row['site_id']
serial_number = row['serial_number']
manufacturer_id = row['manufacturer_id']
device_status = row['device_status']
print(f"Adding device: {device_name} to site ID: {site_id}")
add_device(device_name, device_type_id, role_id, site_id, serial_number, manufacturer_id, device_status)
except KeyError as e:
error_message = f"Missing column in row {index}: {e}"
print(error_message)
with open('error_devices.txt', 'a') as error_file:
error_file.write(f"{error_message}\n")
except Exception as e:
error_message = f"Error processing row {index}: {e}"
print(error_message)
with open('error_devices.txt', 'a') as error_file:
error_file.write(f"{error_message}\n")