Debian Codegraph @

hpilo_cli

raw ◀ ▶
2 Debian patches touch this file
1 #!/usr/bin/python
2 #
3 # (c) 2011-2020 Dennis Kaarsemaker <[email protected]>
4 # see COPYING for license details
5
6 import hpilo
7 import hpilo_fw
8 import getpass
9 import optparse
10 import os
11 from pprint import pprint
12 import ssl
13 import sys
14
15 PY3 = sys.version_info[0] >= 3
16 if PY3:
17 import configparser as ConfigParser
18 from urllib.error import HTTPError
19 basestring = str
20 else:
21 import ConfigParser
22 from urllib2 import HTTPError
23 input = raw_input
24
25 ilo_methods = sorted([x for x in dir(hpilo.Ilo) if not x.startswith('_') and x.islower()])
26
27 def main():
28 usage = """
29 %prog [options] hostname method [args...] [ + method [args...]...]
30 %prog download_rib_firmware ilotype version [version...] """
31
32 p = optparse.OptionParser(usage=usage, add_help_option=False)
33 p.add_option("-l", "--login", dest="login", default=None,
34 help="Username to access the iLO")
35 p.add_option("-p", "--password", dest="password", default=None,
36 help="Password to access the iLO")
37 p.add_option("-i", "--interactive", action="store_true", default=False,
38 help="Prompt for username and/or password if they are not specified.")
39 p.add_option("-c", "--config", dest="config", default="~/.ilo.conf",
40 help="File containing authentication and config details", metavar="FILE")
41 p.add_option("-t", "--timeout", dest="timeout", type="int", default=60,
42 help="Timeout for iLO connections")
43 p.add_option("-j", "--json", dest="format", action="store_const", const="json", default="python",
44 help="Output a json document instead of a python dict")
45 p.add_option("-y", "--yaml", dest="format", action="store_const", const="yaml", default="python",
46 help="Output a yaml document instead of a python dict")
47 p.add_option("-P", "--protocol", dest="protocol", choices=("http","raw","local"), default=None,
48 help="Use the specified protocol instead of autodetecting")
49 p.add_option("-d", "--debug", dest="debug", action="count", default=0,
50 help="Output debug information, repeat to see all XML data")
51 p.add_option("-o", "--port", dest="port", type="int", default=443,
52 help="SSL port to connect to")
53 p.add_option('--ssl-verify', dest="ssl_verify", action="store_true", default=False,
54 help="Verify SSL certificates against the trusted CA's")
55 p.add_option('--ssl-ca-file', dest="ssl_ca_file", default=None,
56 help="CA bundle to validate iLO certificate against, instead of the system CA's")
57 p.add_option('--ssl-ignore-hostname', dest="ssl_ignore_hostname", action='store_true', default=False,
58 help="Don't check if the hostname matches the certificate when verifying SSL certificates")
59 p.add_option("-h", "--help", action="callback", callback=hpilo_help,
60 help="show this help message or help for a method")
61 p.add_option("-H", "--help-methods", action="callback", callback=hpilo_help_methods,
62 help="show all supported methods")
63 p.add_option('--save-response', dest="save_response", default=None, metavar='FILE',
64 help="Store XML output in this file")
65 p.add_option('--read-response', dest="read_response", default=None, metavar='FILE',
66 help="Read XML response from this file instead of the iLO")
67 p.add_option('-v', '--version', action="callback", callback=hpilo_version)
68
69 opts, args = p.parse_args()
70
71 if opts.format == 'json':
72 import json
73 elif opts.format == 'yaml':
74 import yaml
75
76 # Did we get correct arguments?
77 if len(args) < 2:
78 p.error("Not enough arguments")
79
80 if args[1] not in ilo_methods and args[0] != 'download_rib_firmware':
81 p.error("Unknown method: %s" % args[1])
82
83 config = ConfigParser.ConfigParser()
84 if os.path.exists(os.path.expanduser(opts.config)):
85 config.read(os.path.expanduser(opts.config))
86
87 if args[0] == 'download_rib_firmware':
88 if config.has_option('firmware', 'mirror'):
89 hpilo_fw.config(mirror=config.get('firmware', 'mirror'))
90 return download(args[1], args[2:])
91
92 hostname = args.pop(0)
93
94 args_ = list_split(args, '+')
95 calls = []
96
97 for args in args_:
98 method = args.pop(0)
99
100 # Arguments must be passed as param=value pairs that are valid arguments to the methods
101 if sys.version_info[0] >= 3:
102 func = getattr(hpilo.Ilo, method)#.__func__
103 argnames = func.__code__.co_varnames[1:func.__code__.co_argcount]
104 args_with_defaults = []
105 if func.__defaults__:
106 args_with_defaults = argnames[-len(func.__defaults__):]
107 else:
108 func = getattr(hpilo.Ilo, method).im_func
109 argnames = func.func_code.co_varnames[1:func.func_code.co_argcount]
110 args_with_defaults = []
111 if func.func_defaults:
112 args_with_defaults = argnames[-len(func.func_defaults):]
113 params = {}
114 for arg in args:
115 if '=' not in arg:
116 hpilo_help(None, None, method, None, 2)
117 param, val = arg.split('=', 1)
118 # Do we expect structured data?
119 keys = param.split('.')
120 if (len(keys) > 1) != (keys[0] in getattr(func, 'requires_dict', {})):
121 hpilo_help(None, None, method, None, 2)
122
123 if keys[0] not in argnames:
124 hpilo_help(None, None, method, None, 2)
125
126 # Optionally extract values from the config
127 if val.startswith('$') and '.' in val:
128 section, option = val[1:].split('.', 1)
129 if config.has_option(section, option):
130 val = config.get(section, option)
131
132 # Do some type coercion for shell goodness
133 if val.isdigit():
134 val = int(val)
135 else:
136 val = {'true': True, 'false': False}.get(val.lower(), val)
137 params_ = params
138 for key in keys[:-1]:
139 if key not in params_:
140 params_[key] = {}
141 params_ = params_[key]
142
143 params_[keys[-1]] = val
144
145 for name in argnames:
146 if name not in params and name not in args_with_defaults:
147 hpilo_help(None, None, method, None, 2)
148
149 calls.append((method, params))
150
151 # Do we have login information
152 login = None
153 password = None
154 needs_login = bool(opts.read_response)
155 for m, _ in calls:
156 if m != 'xmldata':
157 needs_login = True
158 break
159
160 if hostname == 'localhost':
161 opts.protocol = 'local'
162 needs_login = False
163 if needs_login:
164 if config.has_option('ilo', 'login'):
165 login = config.get('ilo', 'login')
166 if config.has_option('ilo', 'password'):
167 password = config.get('ilo', 'password')
168 if opts.login:
169 login = opts.login
170 if opts.password:
171 password = opts.password
172 if not login or not password:
173 if opts.interactive:
174 while not login:
175 login = input('Login for iLO at %s: ' % hostname)
176 while not password:
177 password = getpass.getpass('Password for %s@%s:' % (login, hostname))
178 else:
179 p.error("No login details provided")
180
181 opts.protocol = {
182 'http': hpilo.ILO_HTTP,
183 'raw': hpilo.ILO_RAW,
184 'local': hpilo.ILO_LOCAL,
185 }.get(opts.protocol, None)
186
187 ssl_context = None
188 if opts.ssl_verify:
189 if sys.version_info < (2,7,9):
190 p.error("SSL verification is only supported in python 2.7.9 or newer")
191 ssl_context = ssl.create_default_context(cafile=opts.ssl_ca_file)
192 ssl_context.options &= ~ssl.OP_NO_SSLv3
193 ssl_context.check_hostname = not opts.ssl_ignore_hostname
194 # import debugme
195
196 ilo = hpilo.Ilo(hostname, login, password, opts.timeout, opts.port, opts.protocol, len(calls) > 1, opts.ssl_verify, ssl_context)
197 ilo.debug = opts.debug
198 ilo.save_response = opts.save_response
199 ilo.read_response = opts.read_response
200 if config.has_option('ilo', 'hponcfg'):
201 ilo.hponcfg = config.get('ilo', 'hponcfg')
202 if config.has_option('firmware', 'mirror'):
203 ilo.firmware_mirror = config.get('firmware', 'mirror')
204
205 def _q(val):
206 if isinstance(val, basestring):
207 return '"%s"' % val.replace("\\","\\\\").replace('"','\\"')
208 else:
209 return str(val)
210
211 for method, params in calls:
212 if method == 'update_rib_firmware':
213 params['progress'] = print_progress
214 results = [getattr(ilo, method)(**params)]
215 if 'progress' in params:
216 params.pop('progress')("")
217
218 if len(calls) > 1:
219 results = ilo.call_delayed()
220
221 if opts.format == 'json':
222 if len(calls) == 1:
223 results = results[0]
224 json.dump(results, sys.stdout)
225 elif opts.format == 'yaml':
226 yaml.dump(results, sys.stdout)
227 else:
228 for method, params in calls:
229 param_str = ', '.join(["%s=%s" % (x[0], _q(x[1])) for x in params.items()])
230 if method.startswith('get') or method == 'certificate_signing_request' or len(calls) == 1:
231 result = results.pop(0)
232 else:
233 result = None
234 if isinstance(result, basestring):
235 print(">>> print(my_ilo.%s(%s))" % (method, param_str))
236 print(result)
237 elif result is None:
238 print(">>> my_ilo.%s(%s)" % (method, param_str))
239 else:
240 print(">>> pprint(my_ilo.%s(%s))" % (method, param_str))
241 pprint(result)
242
243 def hpilo_help(option, opt_str, value, parser, exitcode=0):
244 if not value:
245 if parser and parser.rargs and parser.rargs[0][0] != '-':
246 value = parser.rargs[0]
247 del parser.rargs[0]
248
249 if not value:
250 parser.print_help()
251 else:
252 if value in ilo_methods:
253 import re, textwrap
•254 func = getattr(hpilo.Ilo, value) if PY3 else getattr(hpilo.Ilo, value).im_func
255 code = func.__code__ if PY3 else func.func_code
256 args = ''
257 if code.co_argcount > 1:
258 args = code.co_varnames[:code.co_argcount]
•259 defaults = func.__defaults__ if PY3 else func.func_defaults or []
260 args = ["%s=%s" % (x, x.upper()) for x in args[:len(args)-len(defaults)]] + \
261 ["[%s=%s]" % (x,str(y)) for x, y in zip(args[len(args)-len(defaults):], defaults) if x != 'progress']
262 args = ' ' + ' '.join(args[1:])
263
264 print(textwrap.fill("Ilo.%s%s:" % (value, args), 80))
265 doc = getattr(hpilo.Ilo, value).__doc__ or "No documentation"
266 doc = re.sub(r':[a-z]+:`(.*?)`', r'\1', doc)
267 if 'API note' in doc:
268 doc = doc[:doc.find('API note')].strip()
•269 doc = re.sub(r'\s+', ' ', doc)
270 print(textwrap.fill(doc, 80))
271 else:
272 print("No such method: %s" % value)
273 if parser:
274 parser.exit(exitcode)
275 else:
276 sys.exit(exitcode)
277
278 def hpilo_help_methods(option, opt_str, value, parser):
279 print("""Supported methods:
280 - %s""" % "\n- ".join(ilo_methods))
281 parser.exit()
282
283 def hpilo_version(option, opt_str, value, parser):
284 print(hpilo.__version__)
285 sys.exit()
286
287 def print_progress(text):
288 sys.stdout.write('\r\033[K' + text)
289 sys.stdout.flush()
290
291 def list_split(lst, sep):
292 ret = []
293 while True:
294 try:
295 pos = lst.index(sep)
296 except ValueError:
297 ret.append(lst)
298 break
299 ret.append(lst[:pos])
300 lst = lst[pos+1:]
301 return ret
302
303 def download(ilotype, versions):
304 ilotype = ilotype.lower()
305 config = hpilo_fw.config()
306 if ilotype == 'all':
307 for ilotype in sorted(config.keys()):
308 if (versions == ['all']) == (' ' in ilotype):
309 _download(config, ilotype)
310 else:
311 if not versions:
312 _download(config, ilotype)
313 elif versions == ['all']:
314 for key in sorted(config.keys()):
315 if key.startswith(ilotype + ' '):
316 _download(config, key)
317 else:
318 for version in versions:
319 _download(config, '%s %s' % (ilotype, version))
320
321 def _download(config, key):
322 if key not in config:
323 sys.stderr.write("Unknown ilo/firmware version: %s\n" % key)
324 sys.exit(1)
325 try:
326 if hpilo_fw.download(key, progress=print_progress):
327 print("")
328 else:
329 print("%s firmware version %s was already downloaded" % (key.split()[0], config[key]['version']))
330 except HTTPError as exc:
331 print("\n%s" % str(exc))
332
333 if __name__ == '__main__':
334 main()