-
Notifications
You must be signed in to change notification settings - Fork 49
/
get_power_manager_capable_devices.py
248 lines (196 loc) · 12.6 KB
/
get_power_manager_capable_devices.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
#
# _author_ = Mahendran P <Mahendran_P@Dell.com>
#
# Copyright (c) 2022 Dell EMC Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
#### Synopsis
Script to get the list of devices from OpenManage Enterprise which are capable to be monitored/managed by Power Manager
#### Description
This script exercises the OpenManage Enterprise REST API to get a list of devices currently being managed by OpenManage Enterprise & capable to be monitored/managed by Power Manager.
- For authentication, X-Auth is used over Basic Authentication
- Note that the credentials entered are not stored to disk.
#### Python Example
python Get_Power_Manager_Capable_Devices.py --ip <xx> --username <username> --password <pwd>
Output:
=====================================================
Devices List with Power Manager capablilities
=====================================================
DEVICE_ID SERVICE_TAG MODEL DEVICE_NAME POWER_MANAGER_CAPABILITY
10113 XXXXXXX PowerEdge R640 WIN2K12356.BLR.net Monitor + Management
10106 XXXXXXX PowerEdge R640 WINDOWS2019.BLR.net Monitor only
10105 XXXXXXX PowerEdge R640 WINHIRTK12.BLR.net Monitor + Management
10111 XXXXXXX PowerEdge R640 WINKKLLLL.BLR.net Monitor only
10109 XXXXXXX PowerEdge R640 WIN2019SCALAB.BLR.net Monitor + Management
"""
# Import the modules required for this script
import argparse
import json
import sys
from argparse import RawTextHelpFormatter
# Import the modules required for this script
from requests.packages.urllib3.exceptions import InsecureRequestWarning
try:
import urllib3
import requests
from columnar import columnar
except ModuleNotFoundError:
print("This program requires urllib3, requests, and columnar. To install them on most systems run "
"`pip install requests urllib3`")
sys.exit(0)
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# Funtion to parse the JSON content & store the data
def store_device_elem(device_content):
column_data = []
# For every elements in the Power Manager Devices response, store the details in the table
for device_elem in device_content["value"]:
# Check for Server type devices
if device_elem["Type"] == 1000:
# Check for all capabilities
if (all(cap_bit in str(device_elem["DeviceCapabilities"]) for cap_bit in ['1006', '1105', '1101'])):
device_data = [device_elem["Id"], device_elem["Identifier"], device_elem["Model"],
device_elem["DeviceName"], "Monitor + Management"]
column_data.append(device_data)
# Check if only monitoring capable
elif (all(cap_bit in str(device_elem["DeviceCapabilities"]) for cap_bit in ['1006', '1101'])):
device_data = [device_elem["Id"], device_elem["Identifier"], device_elem["Model"],
device_elem["DeviceName"], "Monitor only"]
column_data.append(device_data)
# Check for Chassis type devices
elif device_elem["Type"] == 2000:
# Check for all capabilities
if (all(cap_bit in str(device_elem["DeviceCapabilities"]) for cap_bit in ['1105', '1101'])):
device_data = [device_elem["Id"], device_elem["Identifier"], device_elem["Model"],
device_elem["DeviceName"], "Monitor + Management"]
column_data.append(device_data)
# Check if only monitoring capable
elif (all(cap_bit in str(device_elem["DeviceCapabilities"]) for cap_bit in ['1101'])):
device_data = [device_elem["Id"], device_elem["Identifier"], device_elem["Model"],
device_elem["DeviceName"], "Monitor only"]
column_data.append(device_data)
return column_data
def get_power_manager_capable_devices(ip_address, user_name, password):
""" Authenticate with OpenManage Enterprise, enumerate and filter power manager capabale devices"""
try:
# Define the Base URL, Session URL & headers
base_uri = 'https://%s' % ip_address
session_url = 'https://%s/api/SessionService/Sessions' % ip_address
headers = {'content-type': 'application/json'}
# Define Payload for posting session API
user_details = {'UserName': user_name,
'Password': password,
'SessionType': 'API'}
# Define the device URL to get top 500 devices (considering scaled OpenManage Enterprise) & then get nextLink in the business logic below to further process the devices
device_url = "https://%s/api/DeviceService/Devices?$top=500" % ip_address
# Define OUTPUT header & data format
output_column_headers = ['Device_ID', 'Service_Tag', 'Model', 'Device_Name', 'Power_Manager_Capability']
output_column_data = []
# Create the session with OpenManage Enterprise
session_info = requests.post(session_url, verify=False,
data=json.dumps(user_details),
headers=headers)
# If session doesn't create, message the user with error
if session_info.status_code != 201 & session_info.status_code != 200:
session_json_data = session_info.json()
if 'error' in session_json_data:
error_content = session_json_data['error']
if '@Message.ExtendedInfo' not in error_content:
print("Unable to create a session with %s. Please try again later" % ip_address)
else:
extended_error_content = error_content['@Message.ExtendedInfo']
print(
"Unable to create a session with %s. See below ExtendedInfo for more information" % ip_address)
print(extended_error_content[0]['Message'])
else:
print("Unable to create a session with %s. Please try again later" % ip_address)
else:
headers['X-Auth-Token'] = session_info.headers['X-Auth-Token']
# Get Devices API call with OpenManage Enterprise
device_response = requests.get(device_url, headers=headers, verify=False)
device_json_data = device_response.json()
# If device API doesn't respond or failed, message the user with error
if device_response.status_code != 201 & device_response.status_code != 200:
if 'error' in device_json_data:
error_content = device_json_data['error']
if '@Message.ExtendedInfo' not in error_content:
print("Unable to retrieve device list from %s" % ip_address)
else:
extended_error_content = error_content['@Message.ExtendedInfo']
print(
"Unable to retrieve device list from %s. See below ExtendedInfo for more information" % ip_address)
print(extended_error_content[0]['Message'])
else:
print("Unable to retrieve device list from %s" % ip_address)
else:
# Get the device count from the JSON response data
device_count = device_json_data['@odata.count']
# If the device count is 0, then error out immediately
if device_count <= 0:
print("No devices managed by %s" % ip_address)
# If the device count is not 0, then get the content & further process it to get device capabilities.
else:
device_content = json.loads(device_response.content)
# If there is no nextLink, then process the content to parse & store the capable Power Manager devices
if '@odata.nextLink' not in device_json_data:
output_column_data = store_device_elem(device_content)
# Else if the next link exist, process to get, parse & store the capable Power Manager devices until the nextLink exhaust.
else:
print(
"\n !!! INFO :: There are more than 500 devices being managed in %s !!! \n It may take several minutes to get the result. Please wait..." % ip_address)
# Process the first set of Devices content to parse & store the capable Power Manager devices
output_column_data = store_device_elem(device_content)
# Define the nextLink URL
next_link_url = base_uri + device_json_data['@odata.nextLink']
# Until nextLink exhaust
while next_link_url:
# Get next set of Devices API call with OpenManage Enterprise
next_link_response = requests.get(next_link_url, headers=headers, verify=False)
if next_link_response.status_code != 200 & next_link_response.status_code != 201:
print("Unable to retrieve device list from nextLink %s" % (next_link_url))
else:
device_content = json.loads(next_link_response.content)
output_column_data += store_device_elem(device_content)
next_link_json_data = next_link_response.json()
if '@odata.nextLink' in next_link_json_data:
next_link_url = base_uri + next_link_json_data['@odata.nextLink']
else:
next_link_url = None
table = columnar(output_column_data, output_column_headers, no_borders=True)
print("\n =====================================================")
print(" Devices List with Power Manager capablilities")
print(" =====================================================")
print(table)
except Exception as error:
print("Unexpected error:", str(error))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter)
parser.add_argument("--ip", "-i", required=True, help="OpenManage Enterprise IP")
parser.add_argument("--username", "-u", required=False, help="Username for OpenManage Enterprise ", default="admin")
parser.add_argument("--password", "-p", required=True, help="Password for OpenManage Enterprise ")
args = parser.parse_args()
print("WARNING: THIS SCRIPT IS EXPERIMENTAL.")
print("The Power Manager scripts were originally internal Dell scripts we then published externally. If you see "
"this message and are using one of these scripts it would be very helpful if you open an issue on GitHub "
"at https://github.com/dell/OpenManage-Enterprise/issues and tell us you are using the script. We have not "
"dedicated any resources to optimizing them but are happy to do so if we know the community is using them. "
"Likewise if you find a bug in one of these scripts feel free to open an issue and we will investigate.")
get_power_manager_capable_devices(args.ip, args.username, args.password)
print("WARNING: THIS SCRIPT IS EXPERIMENTAL.")
print("The Power Manager scripts were originally internal Dell scripts we then published externally. If you see "
"this message and are using one of these scripts it would be very helpful if you open an issue on GitHub "
"at https://github.com/dell/OpenManage-Enterprise/issues and tell us you are using the script. We have not "
"dedicated any resources to optimizing them but are happy to do so if we know the community is using them. "
"Likewise if you find a bug in one of these scripts feel free to open an issue and we will investigate.")