~ubuntu-branches/ubuntu/utopic/pywbem/utopic-updates

« back to all changes in this revision

Viewing changes to wbemcli.py

  • Committer: Bazaar Package Importer
  • Author(s): Mathias Gug
  • Date: 2009-07-28 17:23:55 UTC
  • Revision ID: james.westby@ubuntu.com-20090728172355-f9kv7x14t3ya4ifb
Tags: upstream-0.7.0
ImportĀ upstreamĀ versionĀ 0.7.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/python
 
2
 
 
3
# (C) Copyright 2008 Hewlett-Packard Development Company, L.P.
 
4
 
 
5
# This program is free software; you can redistribute it and/or modify
 
6
# it under the terms of the GNU Lesser General Public License as
 
7
# published by the Free Software Foundation; either version 2 of the
 
8
# License.
 
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
#
 
27
#   wbemcli.py HOSTNAME [-u USERNAME -p PASSWORD] [-n namespace] [--no-ssl] \
 
28
#       [--port PORT]
 
29
#
 
30
# CIM operations can be executed by using the PyWBEM connection object
 
31
# called 'cli' in the global scope.  There are two sets of aliases
 
32
# available for usage in the interpreter. For example the following
 
33
# three commands are equivalent:
 
34
#
 
35
#   >>> cli.EnumerateInstanceNames('SMX_ComputerSystem')
 
36
#   >>> EnumerateInstanceNames('SMX_ComputerSystem')
 
37
#   >>> ein('SMX_ComputerSystem')
 
38
#
 
39
# Pretty-printing of results is also available using the 'pp'
 
40
# function. For example:
 
41
#
 
42
#   >>> cs = ei('SMX_ComputerSystem')[0]
 
43
#   >>> pp(cs.items())
 
44
#   [(u'RequestedState', 12L),
 
45
#    (u'Dedicated', [1L]),
 
46
#    (u'StatusDescriptions', [u'System is Functional']),
 
47
#    (u'IdentifyingNumber', u'6F880AA1-F4F5-11D5-8C45-C0116FBAE02A'),
 
48
#   ...
 
49
#
 
50
 
 
51
import os, stat, sys, string, getpass, errno
 
52
from pywbem import *
 
53
from code import InteractiveConsole
 
54
from optparse import OptionParser
 
55
from pprint import pprint as pp
 
56
 
 
57
# Conditional support of readline module
 
58
 
 
59
have_readline = False
 
60
 
 
61
try:
 
62
    import readline
 
63
    have_readline = True
 
64
except ImportError, arg:
 
65
    pass
 
66
 
 
67
#
 
68
# Parse command line args
 
69
#
 
70
 
 
71
optparser = OptionParser(
 
72
    usage = '%prog HOSTNAME [-u USER -p PASS] [-n NAMESPACE] [--no-ssl]')
 
73
 
 
74
# Username and password
 
75
 
 
76
optparser.add_option('-u', '--user', dest = 'user',
 
77
                     action = 'store', type = 'string',
 
78
                     help = 'user to connect as')
 
79
 
 
80
optparser.add_option('-p', '--password', dest = 'password',
 
81
                     action = 'store', type = 'string',
 
82
                     help = 'password to connect user as')
 
83
 
 
84
# Change the default namespace used
 
85
 
 
86
optparser.add_option('-n', '--namespace', dest = 'namespace',
 
87
                     action = 'store', type = 'string', default = 'root/cimv2',
 
88
                     help = 'default namespace to use')
 
89
 
 
90
# Don't use SSL for remote connections
 
91
 
 
92
optparser.add_option('--no-ssl', dest = 'no_ssl', action = 'store_true',
 
93
                     help = 'don\'t use SSL')
 
94
 
 
95
# Specify non-standard port
 
96
 
 
97
optparser.add_option('--port', dest = 'port', action = 'store', type = 'int',
 
98
                     help = 'port to connect as', default = None)
 
99
 
 
100
# Check usage
 
101
 
 
102
(opts, argv) = optparser.parse_args()
 
103
 
 
104
if len(argv) != 1:
 
105
    optparser.print_usage()
 
106
    sys.exit(1)
 
107
 
 
108
#
 
109
# Set up a client connection
 
110
#
 
111
 
 
112
def remote_connection():
 
113
    """Initiate a remote connection, via PyWBEM."""
 
114
 
 
115
    if argv[0][0] == '/':
 
116
        url = argv[0]
 
117
    else:
 
118
        proto = 'https'
 
119
 
 
120
        if opts.no_ssl:
 
121
            proto = 'http'
 
122
 
 
123
        url = '%s://%s' % (proto, argv[0])
 
124
 
 
125
        if opts.port is not None:
 
126
            url += ':%d' % opts.port
 
127
 
 
128
    creds = None
 
129
 
 
130
    if opts.user is not None and opts.password is None:
 
131
        opts.password = getpass.getpass('Enter password for %s: ' % opts.user)
 
132
 
 
133
    if opts.user is not None or opts.password is not None:
 
134
        creds = (opts.user, opts.password)
 
135
 
 
136
    cli = WBEMConnection(url, creds, default_namespace = opts.namespace)
 
137
 
 
138
    cli.debug = True
 
139
 
 
140
    return cli
 
141
 
 
142
cli = remote_connection()
 
143
 
 
144
#
 
145
# Create some convenient global functions to reduce typing
 
146
#
 
147
 
 
148
def EnumerateInstanceNames(classname, namespace = None):
 
149
    """Enumerate the names of the instances of a CIM Class (including the
 
150
    names of any subclasses) in the target namespace."""
 
151
 
 
152
    return cli.EnumerateInstanceNames(classname, namespace = namespace)
 
153
 
 
154
def EnumerateInstances(classname, namespace = None, LocalOnly = True,
 
155
                       DeepInheritance = True, IncludeQualifiers = False,
 
156
                       IncludeClassOrigin = False):
 
157
    """Enumerate instances of a CIM Class (includeing the instances of
 
158
    any subclasses in the target namespace."""
 
159
 
 
160
    return cli.EnumerateInstances(classname, 
 
161
                                  namespace = namespace,
 
162
                                  DeepInheritance = DeepInheritance,
 
163
                                  IncludeQualifiers = IncludeQualifiers,
 
164
                                  IncludeClassOrigin = IncludeClassOrigin)
 
165
 
 
166
 
 
167
def GetInstance(instancename, LocalOnly = True, IncludeQualifiers = False,
 
168
                IncludeClassOrigin = False):
 
169
    """Return a single CIM instance corresponding to the instance name
 
170
    given."""
 
171
 
 
172
    return cli.GetInstance(instancename, 
 
173
                           LocalOnly = LocalOnly, 
 
174
                           IncludeQualifiers = IncludeQualifiers,
 
175
                           IncludeClassOrigin = IncludeClassOrigin)
 
176
 
 
177
def DeleteInstance(instancename):
 
178
    """Delete a single CIM instance."""
 
179
 
 
180
    return cli.DeleteInstance(instancename)
 
181
 
 
182
def ModifyInstance(*args, **kwargs):
 
183
    return cli.ModifyInstance(*args, **kwargs)
 
184
 
 
185
def CreateInstance(*args, **kwargs):
 
186
    return cli.CreateInstance(*args, **kwargs)
 
187
 
 
188
def InvokeMethod(*args, **kwargs):
 
189
    return cli.InvokeMethod(*args, **kwargs)
 
190
 
 
191
def AssociatorNames(*args, **kwargs):
 
192
    return cli.AssociatorNames(*args, **kwargs)
 
193
 
 
194
def Associators(*args, **kwargs):
 
195
    return cli.Associators(*args, **kwargs)
 
196
 
 
197
def ReferenceNames(*args, **kwargs):
 
198
    return cli.ReferenceNames(*args, **kwargs)
 
199
 
 
200
def References(*args, **kwargs):
 
201
    return cli.References(*args, **kwargs)
 
202
 
 
203
def EnumerateClassNames(*args, **kwargs):
 
204
    return cli.EnumerateClassNames(*args, **kwargs)
 
205
 
 
206
def EnumerateClasses(*args, **kwargs):
 
207
    return cli.EnumerateClasses(*args, **kwargs)
 
208
 
 
209
def GetClass(*args, **kwargs):
 
210
    return cli.GetClass(*args, **kwargs)
 
211
 
 
212
def DeleteClass(*args, **kwargs):
 
213
    return cli.DeleteClass(*args, **kwargs)
 
214
 
 
215
def ModifyClass(*args, **kwargs):
 
216
    return cli.ModifyClass(*args, **kwargs)
 
217
 
 
218
def CreateClass(*args, **kwargs):
 
219
    return cli.CreateClass(*args, **kwargs)
 
220
 
 
221
def EnumerateQualifiers(*args, **kwargs):
 
222
    return cli.EnumerateQualifiers(*args, **kwargs)
 
223
 
 
224
def GetQualifier(*args, **kwargs):
 
225
    return cli.GetQualifier(*args, **kwargs)
 
226
 
 
227
def SetQualifier(*args, **kwargs):
 
228
    return cli.SetQualifier(*args, **kwargs)
 
229
 
 
230
def DeleteQualifier(*args, **kwargs):
 
231
    return cli.DeleteQualifier(*args, **kwargs)
 
232
 
 
233
# Aliases for global functions above
 
234
 
 
235
ein = EnumerateInstanceNames
 
236
ei = EnumerateInstances
 
237
gi = GetInstance
 
238
di = DeleteInstance
 
239
mi = ModifyInstance
 
240
ci = CreateInstance
 
241
 
 
242
im = InvokeMethod
 
243
 
 
244
an = AssociatorNames
 
245
ao = Associators
 
246
rn = ReferenceNames
 
247
re = References
 
248
 
 
249
ecn = EnumerateClassNames
 
250
ec = EnumerateClasses
 
251
gc = GetClass
 
252
dc = DeleteClass
 
253
mc = ModifyClass
 
254
cc = CreateClass
 
255
 
 
256
eq = EnumerateQualifiers
 
257
gq = GetQualifier
 
258
sq = SetQualifier
 
259
dq = DeleteQualifier
 
260
 
 
261
#
 
262
# Enter interactive console
 
263
#
 
264
 
 
265
def get_banner():
 
266
    
 
267
    result = ''
 
268
 
 
269
    # Note how we are connected
 
270
 
 
271
    result += 'Connected to %s' % cli.url
 
272
    if cli.creds is not None:
 
273
        result += ' as %s' % cli.creds[0]
 
274
 
 
275
    return result
 
276
        
 
277
# Read previous command line history
 
278
 
 
279
histfile = '%s/.wbemcli_history' % os.environ['HOME']
 
280
 
 
281
try:
 
282
    if have_readline:
 
283
        readline.read_history_file(histfile)
 
284
except IOError, arg:
 
285
    if arg[0] != errno.ENOENT:
 
286
        raise
 
287
 
 
288
# Interact
 
289
 
 
290
i = InteractiveConsole(globals())
 
291
i.interact(get_banner())
 
292
 
 
293
# Save command line history
 
294
 
 
295
if have_readline:
 
296
    readline.write_history_file(histfile)