source: opsi/server/dass-opsi-tools/usr/bin/opsiclient@ 1184

Last change on this file since 1184 was 1177, checked in by joergs, on May 13, 2015 at 4:46:01 PM

allow setting the inventory number when updating the client

  • Property svn:executable set to *
File size: 17.7 KB
Line 
1#!/usr/bin/env python
2
3# -*- coding: utf-8 -*-
4
5"""ospi-client: performs operation for opsi clients on opsi server via JSON-RPC."""
6
7__author__ = "Joerg Steffens"
8__copyright__ = "Copyright 2012-2015, dass IT GmbH"
9__license__ = "GPL"
10__version__ = "1.1"
11__email__ = "joerg.steffens@dass-it.de"
12
13#self.command("opsi-admin -d method host_createOpsiClient "+ \
14 #computername + " null " + "\\'"+description+"\\'" + \
15 #" \\'created by dassadmin\\' " + mac_address + " " + \
16 #ip_address)
17#self.command("opsi-admin -d method configState_create clientconfig.depot.id " + \
18 #computername + " " + depotName)
19
20import argparse
21import jsonrpc
22import logging
23import os
24from pprint import pprint, pformat
25import time
26
27UrlJsonRpc="https://<username>:<password>@opsi:4447/rpc"
28
29HelpEpilog="WARNING: python-json-rpc is known to have problems with HTTP proxies. In case of problems, make sure, the environment variables http_proxy and/or https_proxy are *not* set."
30
31class OpsiRpc:
32
33 UrlJsonRpcDefault="https://opsi:4447/rpc"
34
35 ProductAttributesCopy = ['actionRequest','actionResult','installationStatus','packageVersion','productVersion']
36
37 def __init__(self, urlJsonRpc = UrlJsonRpcDefault, debug=False ):
38 self.logger=logging.getLogger(__name__)
39 self.debug=debug
40 self.urlJsonRpc=urlJsonRpc
41 self.rpc=jsonrpc.ServiceProxy(self.urlJsonRpc)
42 self.logger.debug( "initialized: " + self.urlJsonRpc )
43
44
45 def list(self):
46 print( "\n".join( self.rpc.getClientIds_list() ) )
47 return True
48
49
50 def getClientsWithProduct( self, product ):
51 return self.rpc.productOnClient_getObjects( [], { "productId": product, "installationStatus": "installed" } )
52
53
54 def listClients( self, product ):
55 if product:
56 for client in self.getClientsWithProduct( product ):
57 print client['clientId']
58 else:
59 return self.list()
60 return True
61
62 def exists(self, src):
63 return len( self.rpc.host_getObjects( [], {"id":src} ) ) == 1
64
65 def info(self, src):
66 if not self.exists( src ):
67 print "failed: opsi client", src, "does not exist"
68 return False
69 print src + ":"
70 host = self.rpc.host_getHashes( [], {"id":src} )[0]
71 print " IP:", host["ipAddress"]
72 print " MAC:", host["hardwareAddress"]
73 print " inventory:", host["inventoryNumber"]
74 print " last seen:", host["lastSeen"]
75 print " notes:", host["notes"]
76 print " depot:", self.clientGetDepot( src )
77
78 print " products:"
79 products = self.getProductOnClient( src, [] )
80 for i in products:
81 print " " + i['productId'] + ":"
82 print " " + i['installationStatus'], "(",
83 if i['actionRequest']:
84 print i['actionRequest'],
85 if i['actionProgress']:
86 print i['actionProgress'],
87 print ")"
88 print " ",
89 pprint( i, indent=8 )
90 return True
91
92 def clean(self, src):
93 if not self.exists( src ):
94 return False
95 products = self.rpc.productOnClient_getObjects( [], { 'clientId': src } )
96 self.rpc.productOnClient_deleteObjects( products )
97
98 products = self.rpc.productPropertyState_getObjects( [], { 'objectId': src } )
99 self.rpc.productPropertyState_deleteObjects( products )
100
101 if self.debug:
102 pprint( self.getProductOnClient( src ) )
103 return True
104
105 def getOpsiConfigserverId(self):
106 # there should always be only one OpsiConfigserver
107 opsiConfigservers=self.rpc.host_getHashes( [], { "type": "OpsiConfigserver" } )
108 try:
109 return opsiConfigservers[0]['id']
110 except (KeyError,IndexError) as e:
111 self.logger.error( "failed to retreive OpsiConfigserver" )
112
113 def createClient(self, name, opsiHostKey, description, notes, hardwareAddress, ipAddress):
114 # self.rpc.host_createOpsiClient( name, opsiHostKey, description, notes, hardwareAddress, ipAddress )
115 self.updateClient( name, opsiHostKey, description, notes, None, hardwareAddress, ipAddress )
116
117 def deleteClient(self, name):
118 self.rpc.host_delete( name )
119
120 def updateClient(self, src, opsiHostKey = None, description = None, notes = None, inventoryNumber = None, hardwareAddress = None, ipAddress = None, depot = None ):
121 obj = {
122 "id" : src,
123 "type" : "OpsiClient",
124 }
125 if opsiHostKey:
126 obj['opsiHostKey'] = opsiHostKey
127 if description:
128 obj['description'] = description
129 if notes:
130 obj['notes'] = notes
131 if inventoryNumber:
132 obj['inventoryNumber'] = inventoryNumber
133 if hardwareAddress:
134 obj['hardwareAddress'] = hardwareAddress
135 if ipAddress:
136 obj['ipAddress'] = ipAddress
137
138 if self.exists( src ):
139 self.rpc.host_updateObject(obj)
140 else:
141 self.rpc.host_insertObject(obj)
142
143 if depot:
144 self.clientSetDepot(src,depot)
145 return True
146
147 def clientGetDepot(self, name):
148 depot = self.rpc.configState_getHashes( [], {
149 "configId": "clientconfig.depot.id",
150 "objectId": name } )
151 try:
152 return depot[0]["values"][0]
153 except (IndexError,KeyError):
154 return self.getOpsiConfigserverId()
155
156 def clientSetDepot(self, name, depot):
157 self.rpc.configState_create( "clientconfig.depot.id", name, depot )
158
159 def copyClient( self, src, dst, ipAddress = None, hardwareAddress = None, depot = None, description = "", copyProperties = True ):
160
161 print "create/update", dst, "from template", src + ":",
162 obj = {
163 "id" : dst,
164 "type" : "OpsiClient",
165 "notes" : "copy of " + src,
166 "description" : description,
167 #"inventoryNumber" : "",
168 }
169 if hardwareAddress:
170 obj['hardwareAddress'] = hardwareAddress
171 if ipAddress:
172 obj['ipAddress'] = ipAddress
173
174 if self.exists( dst ):
175 self.rpc.host_updateObject(obj)
176 else:
177 self.rpc.host_insertObject(obj)
178
179 if depot:
180 self.clientSetDepot(dst,depot)
181
182 if self.debug:
183 pprint( self.getProductOnClient( src ) )
184 self.copyProductOnClient( src, dst )
185 if copyProperties:
186 if self.debug:
187 print "copy product properties"
188 if not depot:
189 # get default Properties from Master Depot Server (OpsiConfigserver)
190 depot = self.getOpsiConfigserverId()
191 self.copyProductPropertyState( src, dst, depot )
192 print "done"
193 return True
194
195 def getProductOnClient( self, client, attributes = ProductAttributesCopy ):
196 return self.rpc.productOnClient_getHashes( [], { 'clientId': client } )
197
198 def copyProductOnClient( self, src, dst, attributes = ProductAttributesCopy ):
199 products_src = self.rpc.productOnClient_getHashes( attributes, { 'clientId': src } )
200 products_dst = []
201 for i in products_src:
202 if self.debug:
203 print i['productId']
204 pprint( i )
205 i['clientId'] = dst
206 products_dst.append(i)
207 self.rpc.productOnClient_createObjects( products_dst )
208 if self.debug:
209 pprint( self.getProductOnClient( dst ) )
210
211
212 def getProductPropertyState( self, client, attributes = [] ):
213 return self.rpc.productPropertyState_getHashes( [], { 'objectId': client } )
214
215
216 def copyProductPropertyState( self, src, dst, default = None, attributes = [] ):
217 if default:
218 productProperties_default = self.getProductPropertyState( default, attributes )
219 else:
220 productProperties_default = []
221 productProperties_src = self.getProductPropertyState( src, attributes )
222 productProperties_dst = []
223 for i in productProperties_src:
224 use_default=False
225 default_value=None
226 for j in productProperties_default:
227 if i['productId'] == j['productId'] and i["propertyId"] == j["propertyId"]:
228 default_value = j['values']
229 if i['values'] == j['values']:
230 use_default=True
231 if self.debug:
232 print i['productId'], "-", i["propertyId"] + ": ", pformat(i["values"]),
233 if use_default:
234 print "(use default)"
235 else:
236 print "(set, default:", default_value, ")"
237 if not use_default:
238 i['objectId'] = dst
239 productProperties_dst.append(i)
240 self.rpc.productPropertyState_createObjects( productProperties_dst )
241 if self.debug:
242 pprint( self.getProductPropertyState( dst ) )
243
244
245 def getClientProductProperty( self, client, product ):
246 return self.rpc.getProductProperties_hash( product, [ client ] )
247
248 def setProductPropertiesOnClient( self, dst, product, properties ):
249 self.rpc.setProductProperties(product,properties,dst)
250
251 def setProductPropertyOnClient( self, dst, product, prop, value):
252 self.rpc.setProductProperty(product,prop,value,dst)
253
254
255 def write_client_conf( self, fd, client, properties ):
256 #Client {
257 #Name = ting-fd
258 #Address = ting.dass-it
259 #FDPort = 9102
260 #Catalog = MyCatalog
261 #Password = "D5w2V5w6B8a9H5Z"
262 #File Retention = 6 months
263 #Job Retention = 6 months
264 #AutoPrune = yes
265 #}
266 params = [ "FDPort", "FileRetention", "JobRetention", "AutoPrune" ]
267 fd.write( "Client {\n" )
268 fd.write( ' Name = "' + properties['filedaemon_full_name'] + '"' + "\n" )
269 fd.write( ' Address = "' + client['clientId'] + '"' + "\n" )
270 # ipAddress: method host_getObjects [] '{"id":client['clientId']}'
271 #print " # Address =", ipAddress
272 fd.write( ' Password = "' + properties['filedaemon_full_password'] + '"' + "\n" )
273 try:
274 catalog = properties['catalog']
275 except KeyError:
276 catalog = "MyCatalog"
277 fd.write( ' Catalog = "' + catalog + '"' + "\n" )
278 for i in params:
279 try:
280 fd.write( ' ' + i + ' = "' + properties[i.lower()] + '"' + "\n" )
281 except KeyError:
282 fd.write( ' # ' + i + " = \n" )
283 fd.write( "}\n")
284 fd.write( "\n" )
285
286
287 def write_job_conf( self, fd, client, properties ):
288 #Job {
289 #FileSet = "tingfileset"
290 #Name = "ting"
291 #Client = ting-fd
292 #JobDefs = "LaptopJob"
293 ## Write Bootstrap = "/var/lib/bacula/ting.bsr"
294 #}
295 params = [ "Fileset", "JobDefs" ]
296 fd.write( "Job {" + "\n" )
297 fd.write( ' Name = "' + client['clientId'] + '-job"' + "\n" )
298 fd.write( ' Client = "' + properties['filedaemon_full_name'] + '"' + "\n" )
299 for i in params:
300 fd.write( " " )
301 try:
302 if not properties[i.lower()]:
303 fd.write( "# " )
304 fd.write( i + ' = "' + properties[i.lower()] + '"' + "\n" )
305 except KeyError:
306 fd.write( "# " + i + " = " + "\n" )
307 fd.write( "}" + "\n" )
308 fd.write( "\n" )
309
310
311 def write_config_file_header( self, fd ):
312 try:
313 fd.write( "#\n" )
314 fd.write( "# automatically generated at {0}\n".format( time.asctime() ) )
315 fd.write( "#\n\n" )
316 except BaseException as e:
317 self.logger.exception( "failed to create files" )
318 return False
319 return True
320
321
322 def createBaculaConfigFiles( self ):
323 clientsWithBacula=self.getClientsWithProduct( "bacula" )
324 if clientsWithBacula:
325 try:
326 file_opsi_clients = open('opsi-clients-generated.conf', 'w')
327 self.write_config_file_header( file_opsi_clients )
328
329 file_opsi_jobs = open('opsi-jobs-generated.conf', 'w')
330 self.write_config_file_header( file_opsi_jobs )
331 except BaseException as e:
332 self.logger.exception( "failed to create files" )
333 return False
334 for client in clientsWithBacula:
335 clientId = client['clientId']
336 try:
337 clientBaculaProperties=self.getClientProductProperty( clientId, "bacula" )
338 except ValueError as e:
339 self.logger.warn( "%s: no valid information found: %s" %(clientId, e) )
340 else:
341 if clientBaculaProperties:
342 #pprint( clientBaculaProperties )
343 self.write_client_conf( file_opsi_clients, client, clientBaculaProperties )
344 self.write_job_conf( file_opsi_jobs, client, clientBaculaProperties )
345 self.logger.info( "%s: OK" % clientId )
346 else:
347 self.logger.warn( "%s: failed: no product properties defined" %(clientId) )
348 return True
349
350
351
352if __name__ == '__main__':
353 logging.basicConfig(format='%(message)s')
354 logger = logging.getLogger(__name__)
355 logger.setLevel(logging.INFO)
356
357 parser = argparse.ArgumentParser(description='Command line tool for OPSI configuration.', epilog=HelpEpilog )
358
359 parser.add_argument( '--debug', action='store_true', help="enable debugging output" )
360
361 parser_url = parser.add_mutually_exclusive_group(required=True)
362 parser_url.add_argument( '--url', help="OPSI Server JSON-RPC url, in following format: " + UrlJsonRpc )
363
364 parser_url.add_argument( '--server', help="OPSI Server (instead of URL)" )
365 username_default=os.getlogin()
366
367 parser.add_argument( '--username', help="username (instead of URL), default: " + username_default, default=username_default )
368 parser.add_argument( '--password', help="password (instead of URL)" )
369
370 subparsers = parser.add_subparsers(title='subcommands',
371 description='valid subcommands',
372 help='additional help',
373 dest='subcommand' )
374
375 parser_clean = subparsers.add_parser('clean', help='remove all product states from a opsi client' )
376 parser_clean.add_argument( 'src', help="source opsi client to clean" )
377
378 parser_copy = subparsers.add_parser('copy', help='copy/create a opsi client from a template opsi client')
379 parser_copy.add_argument( 'src', help="source/template opsi client" )
380 parser_copy.add_argument( 'dst', help="opsi client to be created" )
381 parser_copy.add_argument( '--ip', help="IP address of the new opsi client" )
382 parser_copy.add_argument( '--mac', help="MAC address of the new opsi client" )
383 parser_copy.add_argument( '--depot', help="depot server the new opsi client should be located" )
384 #parser_copy.add_argument( '--no-properties', action='store_false', help="don't copy product properties" )
385
386 parser_createBaculaConfigFiles = subparsers.add_parser('createBaculaConfigFiles', help='create Bacula config files for all clients that have bacula installed')
387
388 parser_exists = subparsers.add_parser('exists', help='check, if a opsi clients exists' )
389 parser_exists.add_argument( 'src', help="source opsi client" )
390 #parser_list = subparsers.add_parser('list', help='list all opsi clients' )
391
392 parser_listClients = subparsers.add_parser('listClients', help='list opsi clients')
393 parser_listClients.add_argument( '--product', help="only list clients, that have product installed" )
394
395 parser_info = subparsers.add_parser('info', help='print information about a opsi client' )
396 parser_info.add_argument( 'src', help="opsi client" )
397
398 parser_update = subparsers.add_parser('update', help='update/create a opsi client')
399 parser_update.add_argument( 'src', help="opsi client to be created/updated" )
400 parser_update.add_argument( '--ip', help="IP address of the opsi client" )
401 parser_update.add_argument( '--mac', help="MAC address of the opsi client" )
402 parser_update.add_argument( '--description', help="a description of the client" )
403 parser_update.add_argument( '--notes', help="notes about the client" )
404 parser_update.add_argument( '--inventory', help="inventory number" )
405 parser_update.add_argument( '--depot', help="depot server the opsi client should be located" )
406
407 args = parser.parse_args()
408
409 if args.debug:
410 logger.setLevel(logging.DEBUG)
411
412 url=args.url
413 if (not url):
414 if args.server:
415 account=""
416 if args.username and args.password:
417 account=args.username + ":" + args.password + "@"
418 elif args.username:
419 account=args.username + "@"
420 url="https://" + account + args.server + ":4447/rpc"
421 else:
422 parser.error( "argument --url is required" )
423
424 opsi=OpsiRpc( url, args.debug )
425
426 result = True
427
428 try:
429 if args.subcommand == "clean":
430 result = opsi.clean( args.src )
431 elif args.subcommand == "copy":
432 result = opsi.copyClient( args.src, args.dst, args.ip, args.mac, args.depot )
433 elif args.subcommand == "createBaculaConfigFiles":
434 result = opsi.createBaculaConfigFiles()
435 elif args.subcommand == "exists":
436 result = opsi.exists( args.src )
437 elif args.subcommand == "list":
438 result = opsi.list()
439 elif args.subcommand == "listClients":
440 result = opsi.listClients( args.product )
441 elif args.subcommand == "info":
442 result = opsi.info( args.src )
443 elif args.subcommand == "update":
444 result = opsi.updateClient( args.src, None, args.description, args.notes, args.inventory, args.mac, args.ip, args.depot )
445 else:
446 print "not yet implemented"
447 except IOError as e:
448 result = False
449 # connection refused
450 print "failed:", e
451
452 if args.debug: print result
453
454 if result:
455 exit(0)
456 else:
457 exit(1)
Note: See TracBrowser for help on using the repository browser.