Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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

0 comments on commit 234e30f

Please sign in to comment.
Something went wrong with that request. Please try again.