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

Last change on this file since 1174 was 1174, checked in by joergs, on Feb 18, 2015 at 4:43:07 PM

only copy properties that differ from default settings

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