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

Last change on this file since 1156 was 1118, checked in by slederer, on Nov 12, 2012 at 11:43:49 AM

opsiclient: zwei Methoden hinzugefügt, die vom dassadmin-Opsi-Plugin zum Setzen von Properties genutzt werden

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