File: wbemcli.py

package info (click to toggle)
pywbem 0.8.0~dev650-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, jessie, jessie-kfreebsd, stretch
  • size: 872 kB
  • ctags: 1,115
  • sloc: python: 10,652; xml: 101; makefile: 19
file content (295 lines) | stat: -rwxr-xr-x 8,009 bytes parent folder | download
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#!/usr/bin/python

# (C) Copyright 2008 Hewlett-Packard Development Company, L.P.

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; version 2 of the License.
   
# 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
# Lesser General Public License for more details.
   
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

# Author: Tim Potter <tpot@hp.com>

#
# A small utility to wrap up a PyWBEM session in a Python interactive
# console.
#
# Usage: 
#
#   wbemcli.py HOSTNAME [-u USERNAME -p PASSWORD] [-n namespace] [--no-ssl] \
#       [--port PORT]
#
# CIM operations can be executed by using the PyWBEM connection object
# called 'cli' in the global scope.  There are two sets of aliases
# available for usage in the interpreter. For example the following
# three commands are equivalent:
#
#   >>> cli.EnumerateInstanceNames('SMX_ComputerSystem')
#   >>> EnumerateInstanceNames('SMX_ComputerSystem')
#   >>> ein('SMX_ComputerSystem')
#
# Pretty-printing of results is also available using the 'pp'
# function. For example:
#
#   >>> cs = ei('SMX_ComputerSystem')[0]
#   >>> pp(cs.items())
#   [(u'RequestedState', 12L),
#    (u'Dedicated', [1L]),
#    (u'StatusDescriptions', [u'System is Functional']),
#    (u'IdentifyingNumber', u'6F880AA1-F4F5-11D5-8C45-C0116FBAE02A'),
#   ...
#

import os, stat, sys, string, getpass, errno
from pywbem import *
from code import InteractiveConsole
from optparse import OptionParser
from pprint import pprint as pp

# Conditional support of readline module

have_readline = False

try:
    import readline
    have_readline = True
except ImportError, arg:
    pass

#
# Parse command line args
#

optparser = OptionParser(
    usage = '%prog HOSTNAME [-u USER -p PASS] [-n NAMESPACE] [--no-ssl]')

# Username and password

optparser.add_option('-u', '--user', dest = 'user',
                     action = 'store', type = 'string',
                     help = 'user to connect as')

optparser.add_option('-p', '--password', dest = 'password',
                     action = 'store', type = 'string',
                     help = 'password to connect user as')

# Change the default namespace used

optparser.add_option('-n', '--namespace', dest = 'namespace',
                     action = 'store', type = 'string', default = 'root/cimv2',
                     help = 'default namespace to use')

# Don't use SSL for remote connections

optparser.add_option('--no-ssl', dest = 'no_ssl', action = 'store_true',
                     help = 'don\'t use SSL')

# Specify non-standard port

optparser.add_option('--port', dest = 'port', action = 'store', type = 'int',
                     help = 'port to connect as', default = None)

# Check usage

(opts, argv) = optparser.parse_args()

if len(argv) != 1:
    optparser.print_usage()
    sys.exit(1)

#
# Set up a client connection
#

def remote_connection():
    """Initiate a remote connection, via PyWBEM."""

    if argv[0][0] == '/':
        url = argv[0]
    else:
        proto = 'https'

        if opts.no_ssl:
            proto = 'http'

        url = '%s://%s' % (proto, argv[0])

        if opts.port is not None:
            url += ':%d' % opts.port

    creds = None

    if opts.user is not None and opts.password is None:
        opts.password = getpass.getpass('Enter password for %s: ' % opts.user)

    if opts.user is not None or opts.password is not None:
        creds = (opts.user, opts.password)

    cli = WBEMConnection(url, creds, default_namespace = opts.namespace)

    cli.debug = True

    return cli

cli = remote_connection()

#
# Create some convenient global functions to reduce typing
#

def EnumerateInstanceNames(classname, namespace = None):
    """Enumerate the names of the instances of a CIM Class (including the
    names of any subclasses) in the target namespace."""

    return cli.EnumerateInstanceNames(classname, namespace = namespace)

def EnumerateInstances(classname, namespace = None, LocalOnly = True,
                       DeepInheritance = True, IncludeQualifiers = False,
                       IncludeClassOrigin = False):
    """Enumerate instances of a CIM Class (includeing the instances of
    any subclasses in the target namespace."""

    return cli.EnumerateInstances(classname, 
                                  namespace = namespace,
                                  DeepInheritance = DeepInheritance,
                                  IncludeQualifiers = IncludeQualifiers,
                                  IncludeClassOrigin = IncludeClassOrigin)


def GetInstance(instancename, LocalOnly = True, IncludeQualifiers = False,
                IncludeClassOrigin = False):
    """Return a single CIM instance corresponding to the instance name
    given."""

    return cli.GetInstance(instancename, 
                           LocalOnly = LocalOnly, 
                           IncludeQualifiers = IncludeQualifiers,
                           IncludeClassOrigin = IncludeClassOrigin)

def DeleteInstance(instancename):
    """Delete a single CIM instance."""

    return cli.DeleteInstance(instancename)

def ModifyInstance(*args, **kwargs):
    return cli.ModifyInstance(*args, **kwargs)

def CreateInstance(*args, **kwargs):
    return cli.CreateInstance(*args, **kwargs)

def InvokeMethod(*args, **kwargs):
    return cli.InvokeMethod(*args, **kwargs)

def AssociatorNames(*args, **kwargs):
    return cli.AssociatorNames(*args, **kwargs)

def Associators(*args, **kwargs):
    return cli.Associators(*args, **kwargs)

def ReferenceNames(*args, **kwargs):
    return cli.ReferenceNames(*args, **kwargs)

def References(*args, **kwargs):
    return cli.References(*args, **kwargs)

def EnumerateClassNames(*args, **kwargs):
    return cli.EnumerateClassNames(*args, **kwargs)

def EnumerateClasses(*args, **kwargs):
    return cli.EnumerateClasses(*args, **kwargs)

def GetClass(*args, **kwargs):
    return cli.GetClass(*args, **kwargs)

def DeleteClass(*args, **kwargs):
    return cli.DeleteClass(*args, **kwargs)

def ModifyClass(*args, **kwargs):
    return cli.ModifyClass(*args, **kwargs)

def CreateClass(*args, **kwargs):
    return cli.CreateClass(*args, **kwargs)

def EnumerateQualifiers(*args, **kwargs):
    return cli.EnumerateQualifiers(*args, **kwargs)

def GetQualifier(*args, **kwargs):
    return cli.GetQualifier(*args, **kwargs)

def SetQualifier(*args, **kwargs):
    return cli.SetQualifier(*args, **kwargs)

def DeleteQualifier(*args, **kwargs):
    return cli.DeleteQualifier(*args, **kwargs)

# Aliases for global functions above

ein = EnumerateInstanceNames
ei = EnumerateInstances
gi = GetInstance
di = DeleteInstance
mi = ModifyInstance
ci = CreateInstance

im = InvokeMethod

an = AssociatorNames
ao = Associators
rn = ReferenceNames
re = References

ecn = EnumerateClassNames
ec = EnumerateClasses
gc = GetClass
dc = DeleteClass
mc = ModifyClass
cc = CreateClass

eq = EnumerateQualifiers
gq = GetQualifier
sq = SetQualifier
dq = DeleteQualifier

#
# Enter interactive console
#

def get_banner():
    
    result = ''

    # Note how we are connected

    result += 'Connected to %s' % cli.url
    if cli.creds is not None:
        result += ' as %s' % cli.creds[0]

    return result
        
# Read previous command line history

histfile = '%s/.wbemcli_history' % os.environ['HOME']

try:
    if have_readline:
        readline.read_history_file(histfile)
except IOError, arg:
    if arg[0] != errno.ENOENT:
        raise

# Interact

i = InteractiveConsole(globals())
i.interact(get_banner())

# Save command line history

if have_readline:
    readline.write_history_file(histfile)