Permalink
Browse files

Another reusable part of serverdb2 has been split off

I use this code to manage iLO interfaces. It's currently nowhere near
complete but more commits should follow soon.
  • Loading branch information...
0 parents commit 234e30f472d3e192cec476c475b7bdb481634769 @seveas committed Dec 2, 2011
Showing with 877 additions and 0 deletions.
  1. +5 −0 .gitignore
  2. +15 −0 COPYING
  3. +1 −0 MANIFEST.in
  4. +28 −0 README
  5. +130 −0 docs/Makefile
  6. +216 −0 docs/conf.py
  7. +115 −0 docs/index.rst
  8. +244 −0 hpilo.py
  9. +97 −0 hpilo_cli
  10. +3 −0 ilo.conf.example
  11. +23 −0 setup.py
5 .gitignore
@@ -0,0 +1,5 @@
+*.pyc
+docs/_build
+build
+dist
+MANIFEST
15 COPYING
@@ -0,0 +1,15 @@
+python-hpilo - Manage iLO interfaces from python code
+Copyright (C) 2011 Dennis Kaarsemaker <dennis@kaarsemaker.net>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
1 MANIFEST.in
@@ -0,0 +1 @@
+include docs/index.rst
28 README
@@ -0,0 +1,28 @@
+Accessing HP iLO interfaces from python
+=======================================
+
+This module will make it easy for you to access the Integrated Lights Out
+management interface of your HP hardware. It supports iLO, iLO 2 and iLO 3 and
+It uses the XML interface to access and change the iLO.
+
+HP, Integrated Lights out and iLO are trademarks of HP, with whom the author of
+this software is not affiliated in any way other than using some of their
+hardware.
+
+Installing
+----------
+
+The software is easy to install from github:
+
+$ git clone git://github.com/seveas/python-hpilo
+$ cd python-hpilo
+$ python setup.py install
+
+The minimum python version supported is 2.5 as this software uses the
+ElementTree XML library. It is probably possible to use older versions and an
+external ElementTree library, but this is left as an exercise to the reader.
+
+Usage
+-----
+See docs/index.rst or the documentation on
+http://packages.python.org/python-hpilo/ for API documentation and examples.
130 docs/Makefile
@@ -0,0 +1,130 @@
+# Makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line.
+SPHINXOPTS =
+SPHINXBUILD = sphinx-build
+PAPER =
+BUILDDIR = _build
+
+# Internal variables.
+PAPEROPT_a4 = -D latex_paper_size=a4
+PAPEROPT_letter = -D latex_paper_size=letter
+ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+
+.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
+
+help:
+ @echo "Please use \`make <target>' where <target> is one of"
+ @echo " html to make standalone HTML files"
+ @echo " dirhtml to make HTML files named index.html in directories"
+ @echo " singlehtml to make a single large HTML file"
+ @echo " pickle to make pickle files"
+ @echo " json to make JSON files"
+ @echo " htmlhelp to make HTML files and a HTML help project"
+ @echo " qthelp to make HTML files and a qthelp project"
+ @echo " devhelp to make HTML files and a Devhelp project"
+ @echo " epub to make an epub"
+ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+ @echo " latexpdf to make LaTeX files and run them through pdflatex"
+ @echo " text to make text files"
+ @echo " man to make manual pages"
+ @echo " changes to make an overview of all changed/added/deprecated items"
+ @echo " linkcheck to check all external links for integrity"
+ @echo " doctest to run all doctests embedded in the documentation (if enabled)"
+
+clean:
+ -rm -rf $(BUILDDIR)/*
+
+html:
+ $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
+ @echo
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
+
+dirhtml:
+ $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
+ @echo
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
+
+singlehtml:
+ $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
+ @echo
+ @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
+
+pickle:
+ $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
+ @echo
+ @echo "Build finished; now you can process the pickle files."
+
+json:
+ $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
+ @echo
+ @echo "Build finished; now you can process the JSON files."
+
+htmlhelp:
+ $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
+ @echo
+ @echo "Build finished; now you can run HTML Help Workshop with the" \
+ ".hhp project file in $(BUILDDIR)/htmlhelp."
+
+qthelp:
+ $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
+ @echo
+ @echo "Build finished; now you can run "qcollectiongenerator" with the" \
+ ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
+ @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-hpilo.qhcp"
+ @echo "To view the help file:"
+ @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-hpilo.qhc"
+
+devhelp:
+ $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
+ @echo
+ @echo "Build finished."
+ @echo "To view the help file:"
+ @echo "# mkdir -p $$HOME/.local/share/devhelp/python-hpilo"
+ @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-hpilo"
+ @echo "# devhelp"
+
+epub:
+ $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
+ @echo
+ @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
+
+latex:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo
+ @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
+ @echo "Run \`make' in that directory to run these through (pdf)latex" \
+ "(use \`make latexpdf' here to do that automatically)."
+
+latexpdf:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo "Running LaTeX files through pdflatex..."
+ make -C $(BUILDDIR)/latex all-pdf
+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
+
+text:
+ $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
+ @echo
+ @echo "Build finished. The text files are in $(BUILDDIR)/text."
+
+man:
+ $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
+ @echo
+ @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
+
+changes:
+ $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
+ @echo
+ @echo "The overview file is in $(BUILDDIR)/changes."
+
+linkcheck:
+ $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
+ @echo
+ @echo "Link check complete; look for any errors in the above output " \
+ "or in $(BUILDDIR)/linkcheck/output.txt."
+
+doctest:
+ $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
+ @echo "Testing of doctests in the sources finished, look at the " \
+ "results in $(BUILDDIR)/doctest/output.txt."
216 docs/conf.py
@@ -0,0 +1,216 @@
+# -*- coding: utf-8 -*-
+#
+# python-hpilo documentation build configuration file, created by
+# sphinx-quickstart on Thu Dec 1 00:46:51 2011.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys, os
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#sys.path.insert(0, os.path.abspath('.'))
+
+# -- General configuration -----------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+#needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be extensions
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = []
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The encoding of source files.
+#source_encoding = 'utf-8-sig'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = u'python-hpilo'
+copyright = u'2011, Dennis Kaarsemaker'
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The short X.Y version.
+version = '0.1'
+# The full version, including alpha/beta/rc tags.
+release = '0.1'
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+#today_fmt = '%B %d, %Y'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+exclude_patterns = ['_build']
+
+# The reST default role (used for this markup: `text`) to use for all documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+# A list of ignored prefixes for module index sorting.
+#modindex_common_prefix = []
+
+
+# -- Options for HTML output ---------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+html_theme = 'default'
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further. For a list of options available for each theme, see the
+# documentation.
+#html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+#html_theme_path = []
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# A shorter title for the navigation bar. Default is the same as html_title.
+#html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+#html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+#html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_domain_indices = True
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+#html_show_sourcelink = True
+
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
+#html_show_sphinx = True
+
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
+#html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it. The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = None
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'python-hpilodoc'
+
+
+# -- Options for LaTeX output --------------------------------------------------
+
+# The paper size ('letter' or 'a4').
+#latex_paper_size = 'letter'
+
+# The font size ('10pt', '11pt' or '12pt').
+#latex_font_size = '10pt'
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, documentclass [howto/manual]).
+latex_documents = [
+ ('index', 'python-hpilo.tex', u'python-hpilo Documentation',
+ u'Dennis Kaarsemaker', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# If true, show page references after internal links.
+#latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+#latex_show_urls = False
+
+# Additional stuff for the LaTeX preamble.
+#latex_preamble = ''
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_domain_indices = True
+
+
+# -- Options for manual page output --------------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+ ('index', 'python-hpilo', u'python-hpilo Documentation',
+ [u'Dennis Kaarsemaker'], 1)
+]
115 docs/index.rst
@@ -0,0 +1,115 @@
+Accessing HP iLO interfaces from python
+=======================================
+
+This module will make it easy for you to access the Integrated Lights Out
+management interface of your HP hardware. It supports iLO, iLO 2 and iLO 3 and
+It uses the XML interface to access and change the iLO.
+
+A command line interface to this module, :file:`hpilo_cli` makes accessing iLO
+interfaces almost trivial and easy to integrate with non-python scripts.
+
+HP, Integrated Lights out and iLO are trademarks of HP, with whom the author of
+this software is not affiliated in any way other than using some of their
+hardware.
+
+iLO obects
+~~~~~~~~~~
+.. class:: Ilo(hostname, username, password, timeout=60)
+
+The :class:`Ilo` class encapsulates all functionality. It autodetects which iLO
+version is in use and will send the correct messages for that version. Its
+methods are divided into several categories below: getting information,
+changing settings and upgrading firmware.
+
+Getting information
+-------------------
+These functions get various bits of information from your iLO interface. As
+they're easiest to explain by wht they return, I'm limiting the explanations to
+example output.
+
+.. function:: get_all_user_info()
+
+ >>> pprint(my_ilo.get_all_user_info())
+ {'Administrator': {'admin_priv': True,
+ 'config_ilo_priv': True,
+ 'remote_cons_priv': True,
+ 'reset_server_priv': True,
+ 'user_login': 'Administrator',
+ 'user_name': 'Administrator',
+ 'virtual_media_priv': True}}
+
+.. function:: get_all_users()
+
+ >>> pprint(my_ilo.get_all_users())
+ ['Administrator']
+
+.. function:: get_global_settings()
+
+ >>> pprint(my_ilo.get_global_settings())
+ {'authentication_failure_logging': 'Enabled-every 3rd failure',
+ 'enforce_aes': False,
+ 'f8_login_required': False,
+ 'f8_prompt_enabled': True,
+ 'http_port': 80,
+ 'https_port': 443,
+ 'ilo_funct_enabled': True,
+ 'min_password': 8,
+ 'rbsu_post_ip': True,
+ 'remote_console_port': 17990,
+ 'serial_cli_speed': 9600,
+ 'serial_cli_status': 'Enabled-Authentication Required',
+ 'session_timeout': 30,
+ 'ssh_port': 22,
+ 'ssh_status': True,
+ 'virtual_media_port': 17988}
+
+.. function:: get_twofactor_settings()
+
+ >>> pprint(my_ilo.get_twofactor_settings())
+ {'auth_twofactor_enable': False,
+ 'cert_owner_subject': None,
+ 'cert_revocation_check': False}
+
+The commandline interface
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The commandline interface allows you to make calls from your shell or scripts
+written in another language than python. It supports all methods that the
+library has and is used as follows::
+
+ $ hpilo_cli --help
+
+ Usage: hpilo_cli [options] hostname method [args...]
+
+ Supported methods:
+ - get_all_user_info
+ - get_all_users
+ - get_global_settings
+ - get_twofactor_settings
+
+ Options:
+ -l LOGIN, --login=LOGIN
+ Username to access the iLO
+ -p PASSWORD, --password=PASSWORD
+ Password to access the iLO
+ -a FILE, --auth=FILE File containing authentication details
+ -t TIMEOUT, --timeout=TIMEOUT
+ Timeout for iLO connections
+ -j, --json Output a json document instead of a python dict
+ -d, --debug Output debug information, repeat to see all XML data
+ -h, --help show this help message or help for a method
+
+The authentication file is a simple ini file that should look like this::
+
+ [ilo]
+ login = Administrator
+ password = AdminPassword
+
+Using such a file is recommended over using the login/password commandline
+arguments.
+
+Contents:
+=========
+
+.. toctree::
+ :maxdepth: 2
244 hpilo.py
@@ -0,0 +1,244 @@
+# (c) 2011 Dennis Kaarsemaker <dennis@kaarsemaker.net>
+# see COPYING for license details
+
+import socket
+import cStringIO as StringIO
+import sys
+import xml.etree.cElementTree as etree
+
+# Which protocol to use
+ILO_RAW = 1
+ILO_HTTP = 2
+
+class IloError(Exception):
+ pass
+
+class Ilo(object):
+ XML_HEADER = '<?xml version="1.0"?>\r\n'
+ HTTP_HEADER = "POST /ribcl HTTP/1.1\r\nHost: localhost\r\nContent-length: %d\r\nConnection: Close\r\n\r\n"
+
+ def __init__(self, hostname, login, password, timeout=60):
+ self.hostname = hostname
+ self.login = login
+ self.password = password
+ self.timeout = timeout
+ self.debug = 0
+ self.protocol = None
+ self.port = 443
+
+ def __str__(self):
+ return "iLO interface of %s" % self.hostname
+
+ def _debug(self, level, message):
+ if self.debug >= level:
+ print >>sys.stderr, message
+
+ def _request(self, xml):
+ """Given an ElementTree.Element, serialize it and do the request.
+ Returns an ElementTree.Element containing the response"""
+
+ if not self.protocol:
+ # Do a bogus request, using the HTTP protocol. If there is no
+ # header (see special case in communicate(), we should be using the
+ # raw protocol
+ header, data = self._communicate('<RIBCL VERSION="2.0"></RIBCL>', ILO_HTTP)
+ if header:
+ self.protocol = ILO_HTTP
+ else:
+ self.protocol = ILO_RAW
+
+ # Serialize the XML
+ xml = "\r\n".join(etree.tostringlist(xml)) + '\r\n'
+
+ header, data = self._communicate(xml, self.protocol)
+
+ # This thing usually contains multiple XML messages
+ messages = []
+ while data:
+ pos = data.find('<?xml', 5)
+ if pos == -1:
+ message = self._parse_message(data)
+ data = None
+ else:
+ message = self._parse_message(data[:pos])
+ data = data[pos:]
+
+ # _parse_message returns None if a message has no useful content
+ if message is not None:
+ messages.append(message)
+
+ if len(messages) == 1:
+ return header, messages[0]
+
+ return header, messages
+
+ def _communicate(self, xml, protocol):
+ """Set up an https connection and do an HTTP/raw socket request"""
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.settimeout(self.timeout)
+ self._debug(1, "Connecting to %s:%d" % (self.hostname, self.port))
+ try:
+ sock.connect((self.hostname, self.port))
+ except socket.timeout:
+ raise IloError("Timeout connecting to %s:%d" % (self.hostname, self.port))
+ except socket.error, e:
+ raise IloError("Error connecting to %s:%d: %s" % (self.hostname, self.port, str(e)))
+ try:
+ sock = socket.ssl(sock)
+ except socket.sslerror, e:
+ raise IloError("Cannot establish ssl session with %s:%d: %s" % (self.hostname, self.port, e.message))
+
+ msglen = msglen_ = len(self.XML_HEADER + xml)
+ if protocol == ILO_HTTP:
+ http_header = self.HTTP_HEADER % msglen
+ msglen += len(http_header)
+ self._debug(1, "Sending XML request, %d bytes" % msglen)
+
+ if protocol == ILO_HTTP:
+ self._debug(2, http_header)
+ sock.write(http_header)
+
+ self._debug(2, self.XML_HEADER + xml)
+
+ # XML header and data need to arrive in 2 distinct packets
+ sock.write(self.XML_HEADER)
+ sock.write(xml)
+
+ # And grab the data
+ data = ''
+ try:
+ while True:
+ d = sock.read()
+ data += d
+ if not d:
+ break
+ except socket.sslerror: # Connection closed
+ if not data:
+ raise IloError("Communication with %s:%d failed: %s" % (self.hostname, self.port, str(e)))
+
+ self._debug(1, "Received %d bytes" % len(data))
+ self._debug(2, data)
+
+ # Do we have HTTP?
+ if protocol == ILO_HTTP and data.startswith('HTTP/1.1 200'):
+ header, data = data.split('\r\n\r\n', 1)
+ header = [x.split(':', 1) for x in header.split('\r\n')[1:]]
+ header = dict([(x[0].lower(), x[1].strip()) for x in header])
+ if header['transfer-encoding'] == 'chunked':
+ _data, data = data, ''
+ while _data:
+ clen, _data = _data.split('\r\n', 1)
+ clen = int(clen, 16)
+ if clen == 0:
+ break
+ data += _data[:clen]
+ _data = _data[clen+2:]
+
+ elif data.startswith('HTTP/1.1 404'):
+ # We must be using iLO2 or older, they don't do HTTP for XML requests
+ # This case is only triggered by the protocol detection
+ header = None
+ data = ''
+ else:
+ header = None
+ return header, data
+
+
+ def _root_element(self, element, **attrs):
+ """Create a basic XML structure for a message. Return root and innermost element"""
+ root = etree.Element('RIBCL', VERSION="2.0")
+ login = etree.SubElement(root, 'LOGIN', USER_LOGIN=self.login, PASSWORD=self.password)
+ element = etree.SubElement(login, element, **attrs)
+ return root, element
+
+ def _parse_message(self, data):
+ """Parse iLO responses into Element instances and remove useless messages"""
+ # Bug in some ilo versions causes malformed XML
+ if '<RIBCL VERSION="2.22"/>' in data:
+ data = data.replace('<RIBCL VERSION="2.22"/>', '<RIBCL VERSION="2.22">')
+ data = data.strip()
+ if not data:
+ return None
+
+ message = etree.fromstring(data)
+ if message.tag == 'RIBCL':
+ for child in message:
+ # INFORM messages are useless
+ if child.tag == 'INFORM':
+ pass
+ # RESPONE with status 0 also adds no value
+ elif child.tag == 'RESPONSE' and int(child.get('STATUS'), 16) == 0:
+ pass
+ # These are interesting, something went wrong
+ elif child.tag == 'RESPONSE':
+ if 'syntax error' in child.get('MESSAGE') and not self.protocol:
+ # This is triggered when doing protocol detection, ignore
+ pass
+ else:
+ raise IloError("Error communicating with iLO: %s" % child.get('MESSAGE'))
+ # And this type of message is the actual payload.
+ else:
+ return message
+ return None
+ # This shouldn't be reached as all messages are RIBCL messages. But who knows!
+ return message
+
+ def _element_children_to_dict(self, element):
+ """Returns a dict with tag names of all child elements as keys and the
+ VALUE attributes as values. Also does some type normalization."""
+ retval = {}
+ for elt in element:
+ key, val = elt.tag.lower(), elt.get('VALUE', None)
+ if val and val.isdigit():
+ val = int(val)
+ else:
+ val = {'Y': True, 'N': False}.get(val, val)
+ retval[key] = val
+ return retval
+
+ def _element_to_dict(self, element):
+ """Returns a dict with tag attributes as items. Also does some type normalization."""
+ retval = {}
+ for key, val in element.attrib.iteritems():
+ retval[key.lower()] = {'Y': True, 'N': False}.get(val, val)
+ return retval
+
+ def _info_tag(self, infotype, tagname):
+ root, inner = self._root_element(infotype, MODE='read')
+ etree.SubElement(inner, tagname)
+ header, message = self._request(root)
+ return self._element_children_to_dict(message.find(tagname))
+
+
+ def get_global_settings(self):
+ """Get global iLO settings"""
+ return self._info_tag('RIB_INFO', 'GET_GLOBAL_SETTINGS')
+
+ def get_twofactor_settings(self):
+ """Get two-factor authentication settings"""
+ return self._info_tag('RIB_INFO', 'GET_TWOFACTOR_SETTINGS')
+
+ # Doesn't work
+ #def get_all_cables_status(self):
+ # return self._info_tag('SERVER_INFO', 'GET_ALL_CABLES_STATUS')
+
+ def get_all_user_info(self):
+ """Get basic and authorization info of all users"""
+ root, attach = self._root_element('USER_INFO', MODE='read')
+ etree.SubElement(attach, 'GET_ALL_USER_INFO')
+
+ header, message = self._request(root)
+ users = {}
+ for user in message.find('GET_ALL_USER_INFO'):
+ user = self._element_to_dict(user)
+ users[user['user_login']] = user
+ return users
+
+ def get_all_users(self):
+ """Get a list of all loginnames"""
+ root, attach = self._root_element('USER_INFO', MODE='read')
+ etree.SubElement(attach, 'GET_ALL_USERS')
+
+ header, message = self._request(root)
+ users = {}
+ return [x.get('VALUE') for x in message.find('GET_ALL_USERS').findall('USER_LOGIN') if x.get('VALUE')]
97 hpilo_cli
@@ -0,0 +1,97 @@
+#!/usr/bin/python
+#
+# (c) 2011 Dennis Kaarsemaker <dennis@kaarsemaker.net>
+# see COPYING for license details
+
+import ConfigParser
+import hpilo
+import optparse
+import os
+from pprint import pprint
+import sys
+
+ilo_methods = sorted([x for x in dir(hpilo.Ilo) if not x.startswith('_') and x.islower()])
+
+def main():
+ usage = """%%prog [options] hostname method [args...]
+
+Supported methods:
+- %s"""
+
+ usage %= "\n- ".join(ilo_methods)
+
+ p = optparse.OptionParser(usage=usage, add_help_option=False)
+ p.add_option("-l", "--login", dest="login", default=None,
+ help="Username to access the iLO")
+ p.add_option("-p", "--password", dest="password", default=None,
+ help="Password to access the iLO")
+ p.add_option("-a", "--auth", dest="auth", default="~/.ilo.conf",
+ help="File containing authentication details", metavar="FILE")
+ p.add_option("-t", "--timeout", dest="timeout", type="int", default=60,
+ help="Timeout for iLO connections")
+ p.add_option("-j", "--json", dest="json", action="store_true", default=False,
+ help="Output a json document instead of a python dict")
+ p.add_option("-d", "--debug", dest="debug", action="count", default=0,
+ help="Output debug information, repeat to see all XML data")
+ p.add_option("-h", "--help", action="callback", callback=hpilo_help,
+ help="show this help message or help for a method")
+
+ opts, args = p.parse_args()
+
+ if opts.json:
+ import json
+
+ # Did we get correct arguments?
+ if len(args) < 2 or args[1] not in ilo_methods:
+ p.print_help()
+ p.exit()
+
+ hostname, method = args[:2]
+ args = args[2:]
+
+ # Do we have login information
+ login = None
+ password = None
+ if os.path.exists(os.path.expanduser(opts.auth)):
+ cp = ConfigParser.ConfigParser()
+ cp.read(os.path.expanduser(opts.auth))
+ if cp.has_option('ilo', 'login'):
+ login = cp.get('ilo', 'login')
+ if cp.has_option('ilo', 'password'):
+ password = cp.get('ilo', 'password')
+ if opts.login:
+ login = opts.login
+ if opts.password:
+ password = opts.password
+ if not login or not password:
+ p.print_help()
+ p.exit()
+
+ ilo = hpilo.Ilo(hostname, login, password, opts.timeout)
+ ilo.debug = opts.debug
+ result = getattr(ilo, method)()
+ if opts.json:
+ json.dump(result, sys.stdout)
+ else:
+ print ">>> pprint(my_ilo.%s())" % method
+ pprint(result)
+
+
+def hpilo_help(option, opt_str, value, parser):
+ assert value is None
+ if parser.rargs and parser.rargs[0][0] != '-':
+ value = parser.rargs[0]
+ del parser.rargs[0]
+
+ if not value:
+ parser.print_help()
+ else:
+ if value in ilo_methods:
+ print "Ilo.%s:" % value
+ print getattr(hpilo.Ilo, value).__doc__
+ else:
+ print "No such method: %s" % value
+ parser.exit()
+
+if __name__ == '__main__':
+ main()
3 ilo.conf.example
@@ -0,0 +1,3 @@
+[ilo]
+login = Administrator
+password = AdminPassword
23 setup.py
@@ -0,0 +1,23 @@
+#!/usr/bin/python
+
+from distutils.core import setup
+
+setup(name = "python-hpilo",
+ version = "0.1.0",
+ author = "Dennis Kaarsemaker",
+ author_email = "dennis@kaarsemaker.net",
+ url = "http://github.com/seveas/python-hpilo",
+ description = "Accessing HP iLO interfaces from python",
+ py_modules = ["hpilo"],
+ scripts = ["hpilo_cli"],
+ classifiers = [
+ 'Development Status :: 3 - Alpha',
+ 'Intended Audience :: Developers',
+ 'Intended Audience :: System Administrators',
+ 'License :: OSI Approved :: GNU General Public License (GPL)',
+ 'Programming Language :: Python :: 2',
+ 'Topic :: System :: Hardware',
+ 'Topic :: System :: Systems Administration',
+ 'Topic :: System :: Networking',
+ ]
+)

0 comments on commit 234e30f

Please sign in to comment.