Package pywbem :: Module wbemcli

[frames] | no frames]

# Source Code for Module pywbem.wbemcli

      1  #!/usr/bin/env python
      2  #
      3  # (C) Copyright 2008 Hewlett-Packard Development Company, L.P.
      4  #
      5  # This library is free software; you can redistribute it and/or
      6  # modify it under the terms of the GNU Lesser General Public
      7  # License as published by the Free Software Foundation; either
      8  # version 2.1 of the License, or (at your option) any later version.
      9  #
     10  # This program is distributed in the hope that it will be useful, but
     11  # WITHOUT ANY WARRANTY; without even the implied warranty of
     12  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     13  # Lesser General Public License for more details.
     14  #
     15  # You should have received a copy of the GNU Lesser General Public
     16  # License along with this program; if not, write to the Free Software
     17  # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
     18  #
     19  # Author: Tim Potter <tpot@hp.com>
     20  #
     21
     22  """A small utility to wrap up a PyWBEM session in a Python interactive
     23  console.
     24
     25  Usage:
     26    wbemcli.py HOSTNAME [-u USERNAME -p PASSWORD] [-n namespace] [--no-ssl] \
     27        [--port PORT]
     28
     29  The utility creates a ``pywbem.WBEMConnection`` object for the specified
     30  WBEM server location. Subsequent operatoins then use that connection.
     31
     32  There are two sets of aliases available for usage in the interpreter. For
     33  example, the following two commands are equivalent:
     34
     35    >>> EnumerateInstanceNames('SMX_ComputerSystem')
     36    >>> ein('SMX_ComputerSystem')
     37
     38  Pretty-printing of results is also available using the 'pp'
     39  function. For example:
     40
     41    >>> cs = ei('SMX_ComputerSystem')[0]
     42    >>> pp(cs.items())
     43    [(u'RequestedState', 12L),
     44     (u'Dedicated', [1L]),
     45     (u'StatusDescriptions', [u'System is Functional']),
     46     (u'IdentifyingNumber', u'6F880AA1-F4F5-11D5-8C45-C0116FBAE02A'),
     47    ...
     48  """
     49
     50  import os
     51  import sys
     52  import getpass
     53  import errno
     54  import code
     55  import optparse
     56
     57  # Conditional support of readline module
     58  _HAVE_READLINE = False
     59  try:
     60      import readline
     61      _HAVE_READLINE = True
     62  except ImportError, arg:
     63      pass
     64
     65  import pywbem
     66
     67  # Additional symbols for use in the interactive session
     68  from pprint import pprint as pp
     69
     70  __all__ = []
     71
     72  _CONN = None
     73
     74 -def remote_connection(argv, opts):
     75      """Initiate a remote connection, via PyWBEM."""
     76
     77      global _CONN
     78
     79      if argv[0][0] == '/':
     80          url = argv[0]
     81      else:
     82          proto = 'https'
     83
     84          if opts.no_ssl:
     85              proto = 'http'
     86
     87          url = '%s://%s' % (proto, argv[0])
     88
     89          if opts.port is not None:
     90              url += ':%d' % opts.port
     91
     92      creds = None
     93
     94      if opts.user is not None and opts.password is None:
     95          opts.password = getpass.getpass('Enter password for %s: ' % opts.user)
     96
     97      if opts.user is not None or opts.password is not None:
     98          creds = (opts.user, opts.password)
     99
    100      _CONN = pywbem.WBEMConnection(url, creds, default_namespace=opts.namespace)
    101
    102      _CONN.debug = True
    103
    104      return _CONN
    105
    106  #
    107  # Create some convenient global functions to reduce typing
    108  #
    109
    110 -def EnumerateInstanceNames(classname, namespace=None):
    111      """Enumerate the names of the instances of a CIM Class (including the
    112      names of any subclasses) in the target namespace."""
    113
    114      global _CONN
    115
    116      return _CONN.EnumerateInstanceNames(classname, namespace=namespace)
    117
    118 -def EnumerateInstances(classname, namespace=None, LocalOnly=True,
    119                         DeepInheritance=True, IncludeQualifiers=False,
    120                         IncludeClassOrigin=False):
    121      """Enumerate instances of a CIM Class (includeing the instances of
    122      any subclasses in the target namespace."""
    123
    124      global _CONN
    125
    126      return _CONN.EnumerateInstances(classname,
    127                                    namespace=namespace,
    128                                    DeepInheritance=DeepInheritance,
    129                                    IncludeQualifiers=IncludeQualifiers,
    130                                    IncludeClassOrigin=IncludeClassOrigin)
    131
    132
    133 -def GetInstance(instancename, LocalOnly=True, IncludeQualifiers=False,
    134                  IncludeClassOrigin=False):
    135      """Return a single CIM instance corresponding to the instance name
    136      given."""
    137
    138      global _CONN
    139
    140      return _CONN.GetInstance(instancename,
    141                             LocalOnly=LocalOnly,
    142                             IncludeQualifiers=IncludeQualifiers,
    143                             IncludeClassOrigin=IncludeClassOrigin)
    144
    145 -def DeleteInstance(instancename):
    146      """Delete a single CIM instance."""
    147
    148      global _CONN
    149
    150      return _CONN.DeleteInstance(instancename)
    151
    152 -def ModifyInstance(*args, **kwargs):
    153      global _CONN
    154      return _CONN.ModifyInstance(*args, **kwargs)
    155
    156 -def CreateInstance(*args, **kwargs):
    157      global _CONN
    158      return _CONN.CreateInstance(*args, **kwargs)
    159
    160 -def InvokeMethod(*args, **kwargs):
    161      global _CONN
    162      return _CONN.InvokeMethod(*args, **kwargs)
    163
    164 -def AssociatorNames(*args, **kwargs):
    165      global _CONN
    166      return _CONN.AssociatorNames(*args, **kwargs)
    167
    168 -def Associators(*args, **kwargs):
    169      global _CONN
    170      return _CONN.Associators(*args, **kwargs)
    171
    172 -def ReferenceNames(*args, **kwargs):
    173      global _CONN
    174      return _CONN.ReferenceNames(*args, **kwargs)
    175
    176 -def References(*args, **kwargs):
    177      global _CONN
    178      return _CONN.References(*args, **kwargs)
    179
    180 -def EnumerateClassNames(*args, **kwargs):
    181      global _CONN
    182      return _CONN.EnumerateClassNames(*args, **kwargs)
    183
    184 -def EnumerateClasses(*args, **kwargs):
    185      global _CONN
    186      return _CONN.EnumerateClasses(*args, **kwargs)
    187
    188 -def GetClass(*args, **kwargs):
    189      global _CONN
    190      return _CONN.GetClass(*args, **kwargs)
    191
    192 -def DeleteClass(*args, **kwargs):
    193      global _CONN
    194      return _CONN.DeleteClass(*args, **kwargs)
    195
    196 -def ModifyClass(*args, **kwargs):
    197      global _CONN
    198      return _CONN.ModifyClass(*args, **kwargs)
    199
    200 -def CreateClass(*args, **kwargs):
    201      global _CONN
    202      return _CONN.CreateClass(*args, **kwargs)
    203
    204 -def EnumerateQualifiers(*args, **kwargs):
    205      global _CONN
    206      return _CONN.EnumerateQualifiers(*args, **kwargs)
    207
    208 -def GetQualifier(*args, **kwargs):
    209      global _CONN
    210      return _CONN.GetQualifier(*args, **kwargs)
    211
    212 -def SetQualifier(*args, **kwargs):
    213      global _CONN
    214      return _CONN.SetQualifier(*args, **kwargs)
    215
    216 -def DeleteQualifier(*args, **kwargs):
    217      global _CONN
    218      return _CONN.DeleteQualifier(*args, **kwargs)
    219
    220  # Aliases for global functions above
    221
    222  ein = EnumerateInstanceNames
    223  ei = EnumerateInstances
    224  gi = GetInstance
    225  di = DeleteInstance
    226  mi = ModifyInstance
    227  ci = CreateInstance
    228
    229  im = InvokeMethod
    230
    231  an = AssociatorNames
    232  ao = Associators
    233  rn = ReferenceNames
    234  re = References
    235
    236  ecn = EnumerateClassNames
    237  ec = EnumerateClasses
    238  gc = GetClass
    239  dc = DeleteClass
    240  mc = ModifyClass
    241  cc = CreateClass
    242
    243  eq = EnumerateQualifiers
    244  gq = GetQualifier
    245  sq = SetQualifier
    246  dq = DeleteQualifier
    247
    248
    249 -def get_banner():
    250      """Return a banner message for the interactive console."""
    251
    252      global _CONN
    253
    254      result = ''
    255
    256      # Note how we are connected
    257      result += 'Connected to %s' % _CONN.url
    258      if _CONN.creds is not None:
    259          result += ' as %s' % _CONN.creds[0]
    260
    261      # Give hint about exiting. Most people exit with 'quit()' which will
    262      # not return from the interact() method, and thus will not write
    263      # the history.
    264      result += '\nPress Ctrl-D to exit'
    265
    266      return result
    267
    268
    269 -def main():
    270      """Main routine, when called as a script."""
    271
    272      global _CONN
    273
    274      # Parse command line args
    275      optparser = optparse.OptionParser(
    276          usage='%prog HOSTNAME [-u USER -p PASS] [-n NAMESPACE] [--no-ssl]')
    277
    278      # Username and password
    279      optparser.add_option('-u', '--user', dest='user',
    280                           action='store', type='string',
    281                           help='user to connect as')
    282      optparser.add_option('-p', '--password', dest='password',
    283                           action='store', type='string',
    284                           help='password to connect user as')
    285
    286      # Change the default namespace used
    287      optparser.add_option('-n', '--namespace', dest='namespace',
    288                           action='store', type='string', default='root/cimv2',
    289                           help='default namespace to use')
    290
    291      # Don't use SSL for remote connections
    292      optparser.add_option('--no-ssl', dest='no_ssl', action='store_true',
    293                           help='don\'t use SSL')
    294
    295      # Specify non-standard port
    296      optparser.add_option('--port', dest='port', action='store', type='int',
    297                           help='port to connect as', default=None)
    298
    299      # Check usage
    300      (opts, argv) = optparser.parse_args()
    301
    302      if len(argv) != 1:
    303          optparser.print_usage()
    304          sys.exit(1)
    305
    306      # Set up a client connection
    307      _CONN = remote_connection(argv, opts)
    308
    309      # Determine file path of history file
    310      home_dir = '.'
    311      if 'HOME' in os.environ:
    312          home_dir = os.environ['HOME'] # Linux
    313      elif 'HOMEPATH' in os.environ:
    314          home_dir = os.environ['HOMEPATH'] # Windows
    315      histfile = '%s/.wbemcli_history' % home_dir
    316
    317      # Read previous command line history
    318      if _HAVE_READLINE:
    319          try:
    320              readline.read_history_file(histfile)
    321          except IOError, arg:
    322              if arg[0] != errno.ENOENT:
    323                  raise
    324
    325      # Interact
    326      i = code.InteractiveConsole(globals())
    327      i.interact(get_banner())
    328
    329      # Save command line history
    330      if _HAVE_READLINE:
    331          readline.write_history_file(histfile)
    332
    333      return 0
    334
    335  if __name__ == '__main__':
    336      exit(main())
    337