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

Last change on this file since 1176 was 1176, checked in by joergs, on Feb 18, 2015 at 7:24:49 PM

added function clientGetDepot

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