-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadtran-inventory.py
234 lines (209 loc) · 8.16 KB
/
adtran-inventory.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!/usr/bin/python3
import logging
import os
import requests
import signal
import time
import threading
import xlsxwriter
from datetime import datetime
from queue import Queue
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from netmiko import ConnectHandler as ch
# not needed if your ssl is truly valid from the machine running the script
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# number of simultaneous ssh connections
num_threads = 25
# This sets up the queue
enclosure_queue = Queue()
# Set up thread lock so that only one thread outputs at a time
lock = threading.Lock()
failures = []
devices = []
start = datetime.now()
inventory = {}
row = 1
col = 0
# create this with librenms under settings/api
auth_token = ''
# this is your librenms URL. https://sitename/api/v0
librenms_api = ''
# list of librenms groups to fetch devices from
groups = ['Adtran']
# groups = ['testbatch']
# need i explain this one?
creds = {
"username": "",
"password": "",
"device_type": "adtran_os",
"conn_timeout": 20,
}
logging.basicConfig(filename='output.log', level=logging.INFO)
req_headers = {
'X-Auth-Token': auth_token
}
def fetch_device(device):
"""
Takes a device_id and fetches information from librenms
API to populate new_device, returns a dictionary new_device
"""
new_device = requests.get(
librenms_api + '/devices/' + str(device),
headers=req_headers,
verify=False,
).json()['devices']
if len(new_device) != 1:
print(f"Error - No such device {device}.")
return new_device[0] # we should only return one device
def polldevice(i, q):
'''
Takes a task number and device object, populates
the inventory list of dicts
'''
global inventory
while True:
dev = q.get()
creds['host'] = dev['hostname']
with lock:
logging.info("Loading: %s (%s)", dev['sysName'], creds['host'])
print(f"Loading: {dev['sysName']} ({creds['host']})")
try:
try:
net_connect = ch(**creds)
except NetMikoTimeoutException:
failures.append(dev)
with lock:
print("Timeout connecting to {dev['sysName']} Count: {len(failures)}")
logging.warning("Timeout connection to device: %s, Count: %s", dev['sysName'], len(failures))
q.task_done()
os.kill(os.getpid(), signal.SIGUSR1)
except NetMikoAuthenticationException:
failures.append(dev)
with lock:
print("\n{}: ERROR: Authentication failed for {}. Stopping script. \n".format(i, dev['hostname']))
logging.warning("Authentcation error on device: %s, Count: %s", dev['sysName'], len(failures))
q.task_done()
os.kill(os.getpid(), signal.SIGUSR1)
result_raw = net_connect.send_command('enable', expect_string='#')
# we overwrite result_raw, but we don't care about the enable output anyway
result_raw = net_connect.send_command('sho system inventory', expect_string='#')
net_connect.disconnect()
for z in result_raw.splitlines():
# we ignore these because adtran helpfully prints every slot twice
if "1/" in z:
if '....' in z:
logging.info('Skipping: %s', z)
continue
elif 'Alarm' in z:
logging.info('Skipping: %s', z)
continue
elif 'SLOT' in z:
logging.info('Skipping: %s', z)
continue
elif 'Minor' in z:
logging.info('Skipping: %s', z)
continue
elif 'Major' in z:
logging.info('Skipping: %s', z)
continue
elif 'Alert' in z:
logging.info('Skipping: %s', z)
continue
result = z.split(', ')
inventory[dev['device_id']].append({
"sysName": dev['sysName'].strip(),
"ip": dev['hostname'].strip(),
"pn": result[0][4:].replace('*', '').strip(), # partnumber - remove *
"type": result[1].strip(), # part type
"slot": result[0][:4].strip(), # slot
"rev": result[2].strip(), # hardware revision
"clei": result[3].strip(), # clei
"serial": result[4].strip(), # serial number
})
logging.info('Added: %s', dev['sysName'])
q.task_done()
except Exception as e:
with lock:
print(f"Fail: {dev['sysName']} Count: {len(failures)} Exception: {e}")
failures.append(dev)
logging.warning("Fail: %s, Count: %s", dev['sysName'], len(failures))
q.task_done()
for group in groups:
print("Fetching devices for group: ", group)
# fetch all device_ids for group 'group'
devicegroups = requests.get(
librenms_api + '/devicegroups/' + str(group),
headers=req_headers,
verify=False,
).json()['devices']
# add all those devices to devices
for dev in devicegroups:
# create a dict entry inventory['device_id'] and make it
# a list to hold inventory items later
inventory[dev['device_id']] = list()
logging.info("created %s", dev['device_id'])
print(f'fetched {len(inventory)} devices.')
for i in range(num_threads):
# Create the thread using 'polldevice' as the function, passing in
# the thread number and queue object as parameters
thread = threading.Thread(target=polldevice, args=(i, enclosure_queue,))
# Set the thread as a background daemon/job
thread.setDaemon(True)
# Start the thread
thread.start()
# For each device add to queue
for dev in inventory:
target = fetch_device(dev)
logging.info("Fetched details for %s", str(dev))
if 'adtran' in target['os'] and 'TA5' in target['sysDescr']:
enclosure_queue.put(target)
else:
print(f"Skipping host {target['sysName']} desc {target['sysDescr']}")
# Wait for all tasks in the queue to be marked as completed (task_done)
enclosure_queue.join()
# set up the xlsx sheet
w = xlsxwriter.Workbook('adtran-inventory.xlsx') # will be overwritten
inv = w.add_worksheet('inventory')
inv.set_column('A:A', 45) # sysname
inv.set_column('B:B', 15) # hostname (IP)
inv.set_column('C:C', 8) # slot
inv.set_column('D:D', 15) # partnum
inv.set_column('E:E', 15) # type
inv.set_column('F:F', 8) # rev
inv.set_column('G:G', 16) # clei
inv.set_column('H:H', 25) # serial
inv.autofilter('A1:H1')
inv.write('A1', 'sysname')
inv.write('B1', 'hostname')
inv.write('C1', 'slot')
inv.write('D1', 'PartNumber')
inv.write('E1', 'Type')
inv.write('F1', 'rev')
inv.write('G1', 'CLEI')
inv.write('H1', 'serial')
# write our spreadsheet data
for d in inventory:
for item in inventory[d]:
# print(f"Item {item}")
try:
inv.write(row, col, item['sysName']) # device sysName from Librenms
inv.write(row, col + 1, item['ip']) # ip address (maps to librenms hostname)
inv.write(row, col + 2, item['slot']) # slot 1/a
inv.write(row, col + 3, item['pn']) # part number
inv.write(row, col + 4, item['type']) # part type
inv.write(row, col + 5, item['rev']) # hardware revision
inv.write(row, col + 6, item['clei']) # clei
inv.write(row, col + 7, item['serial']) # serial number
except IndexError:
print(f"Error writing {dev['sysName']} to spreadsheet.")
w.close()
print("complete.")
end = datetime.now()
print(f"Time: {(end-start)/60}")
if len(failures) > 0:
logging.info("These devices failed: ")
for f in failures:
logging.info('%s hostname %s', f['sysName'], f['hostname'])
print(f"Failed to download {f['sysName']} {f['hostname']}.")
else:
print("Yay! No failures!")