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

Last change on this file since 1177 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
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 )
[1177]115 self.updateClient( name, opsiHostKey, description, notes, None, hardwareAddress, ipAddress )
[1087]116
[1175]117 def deleteClient(self, name):
118 self.rpc.host_delete( name )
119
[1177]120 def updateClient(self, src, opsiHostKey = None, description = None, notes = None, inventoryNumber = None, hardwareAddress = None, ipAddress = None, depot = None ):
[1117]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
[1177]131 if inventoryNumber:
132 obj['inventoryNumber'] = inventoryNumber
[1117]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)
[1174]142
[1117]143 if depot:
144 self.clientSetDepot(src,depot)
145 return True
146
[1176]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()
[1117]155
[1087]156 def clientSetDepot(self, name, depot):
[1174]157 self.rpc.configState_create( "clientconfig.depot.id", name, depot )
[1087]158
[1088]159 def copyClient( self, src, dst, ipAddress = None, hardwareAddress = None, depot = None, description = "", copyProperties = True ):
[1174]160
[1087]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)
[1174]178
[1087]179 if depot:
180 self.clientSetDepot(dst,depot)
[1174]181
[1087]182 if self.debug:
183 pprint( self.getProductOnClient( src ) )
184 self.copyProductOnClient( src, dst )
[1088]185 if copyProperties:
186 if self.debug:
187 print "copy product properties"
[1174]188 if not depot:
189 # get default Properties from Master Depot Server (OpsiConfigserver)
190 depot = self.getOpsiConfigserverId()
191 self.copyProductPropertyState( src, dst, depot )
[1087]192 print "done"
193 return True
194
195 def getProductOnClient( self, client, attributes = ProductAttributesCopy ):
196 return self.rpc.productOnClient_getHashes( [], { 'clientId': client } )
[1110]197
[1087]198 def copyProductOnClient( self, src, dst, attributes = ProductAttributesCopy ):
[1088]199 products_src = self.rpc.productOnClient_getHashes( attributes, { 'clientId': src } )
200 products_dst = []
201 for i in products_src:
[1087]202 if self.debug:
203 print i['productId']
204 pprint( i )
205 i['clientId'] = dst
[1088]206 products_dst.append(i)
207 self.rpc.productOnClient_createObjects( products_dst )
[1087]208 if self.debug:
209 pprint( self.getProductOnClient( dst ) )
[1088]210
[1174]211
[1088]212 def getProductPropertyState( self, client, attributes = [] ):
213 return self.rpc.productPropertyState_getHashes( [], { 'objectId': client } )
[1174]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 = []
[1088]221 productProperties_src = self.getProductPropertyState( src, attributes )
222 productProperties_dst = []
223 for i in productProperties_src:
[1174]224 use_default=False
[1176]225 default_value=None
[1174]226 for j in productProperties_default:
227 if i['productId'] == j['productId'] and i["propertyId"] == j["propertyId"]:
[1176]228 default_value = j['values']
[1174]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:
[1176]236 print "(set, default:", default_value, ")"
[1174]237 if not use_default:
238 i['objectId'] = dst
239 productProperties_dst.append(i)
[1088]240 self.rpc.productPropertyState_createObjects( productProperties_dst )
241 if self.debug:
242 pprint( self.getProductPropertyState( dst ) )
[1110]243
244
245 def getClientProductProperty( self, client, product ):
246 return self.rpc.getProductProperties_hash( product, [ client ] )
247
[1118]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
[1110]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" )
[1087]285
286
[1110]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 ):
[1174]312 try:
[1110]313 fd.write( "#\n" )
[1114]314 fd.write( "# automatically generated at {0}\n".format( time.asctime() ) )
[1110]315 fd.write( "#\n\n" )
[1177]316 except BaseException as e:
[1110]317 self.logger.exception( "failed to create files" )
318 return False
319 return True
320
[1174]321
[1110]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 )
[1174]328
[1110]329 file_opsi_jobs = open('opsi-jobs-generated.conf', 'w')
330 self.write_config_file_header( file_opsi_jobs )
[1174]331 except BaseException as e:
[1110]332 self.logger.exception( "failed to create files" )
333 return False
334 for client in clientsWithBacula:
[1174]335 clientId = client['clientId']
[1110]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
[1047]352if __name__ == '__main__':
[1110]353 logging.basicConfig(format='%(message)s')
354 logger = logging.getLogger(__name__)
355 logger.setLevel(logging.INFO)
356
[1063]357 parser = argparse.ArgumentParser(description='Command line tool for OPSI configuration.', epilog=HelpEpilog )
358
[1047]359 parser.add_argument( '--debug', action='store_true', help="enable debugging output" )
[1028]360
[1110]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
[1050]370 subparsers = parser.add_subparsers(title='subcommands',
371 description='valid subcommands',
372 help='additional help',
373 dest='subcommand' )
[1047]374
[1050]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" )
[1174]377
378 parser_copy = subparsers.add_parser('copy', help='copy/create a opsi client from a template opsi client')
[1050]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" )
[1088]384 #parser_copy.add_argument( '--no-properties', action='store_false', help="don't copy product properties" )
[1174]385
[1110]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' )
[1174]391
[1110]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" )
[1174]394
[1110]395 parser_info = subparsers.add_parser('info', help='print information about a opsi client' )
396 parser_info.add_argument( 'src', help="opsi client" )
[1174]397
[1117]398 parser_update = subparsers.add_parser('update', help='update/create a opsi client')
[1177]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
[1047]407 args = parser.parse_args()
[1177]408
[1110]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" )
[1174]423
[1110]424 opsi=OpsiRpc( url, args.debug )
[1174]425
[1051]426 result = True
427
[1174]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":
[1177]444 result = opsi.updateClient( args.src, None, args.description, args.notes, args.inventory, args.mac, args.ip, args.depot )
[1174]445 else:
446 print "not yet implemented"
447 except IOError as e:
448 result = False
449 # connection refused
450 print "failed:", e
[1050]451
[1174]452 if args.debug: print result
453
[1051]454 if result:
455 exit(0)
456 else:
457 exit(1)
Note: See TracBrowser for help on using the repository browser.