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 |
|
---|
20 | import argparse
|
---|
21 | import jsonrpc
|
---|
22 | import logging
|
---|
23 | import os
|
---|
24 | from pprint import pprint, pformat
|
---|
25 | import time
|
---|
26 |
|
---|
27 | UrlJsonRpc="https://<username>:<password>@opsi:4447/rpc"
|
---|
28 |
|
---|
29 | HelpEpilog="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 |
|
---|
31 | class 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 |
|
---|
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 )
|
---|
96 |
|
---|
97 | products = self.rpc.productPropertyState_getObjects( [], { 'objectId': src } )
|
---|
98 | self.rpc.productPropertyState_deleteObjects( products )
|
---|
99 |
|
---|
100 | if self.debug:
|
---|
101 | pprint( self.getProductOnClient( src ) )
|
---|
102 | return True
|
---|
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 |
|
---|
112 | def createClient(self, name, opsiHostKey, description, notes, hardwareAddress, ipAddress):
|
---|
113 | # self.rpc.host_createOpsiClient( name, opsiHostKey, description, notes, hardwareAddress, ipAddress )
|
---|
114 | self.updateClient( name, opsiHostKey, description, notes, hardwareAddress, ipAddress )
|
---|
115 |
|
---|
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:
|
---|
126 | obj['notes'] = notes
|
---|
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)
|
---|
136 |
|
---|
137 | if depot:
|
---|
138 | self.clientSetDepot(src,depot)
|
---|
139 | return True
|
---|
140 |
|
---|
141 |
|
---|
142 | def clientSetDepot(self, name, depot):
|
---|
143 | self.rpc.configState_create( "clientconfig.depot.id", name, depot )
|
---|
144 |
|
---|
145 | def copyClient( self, src, dst, ipAddress = None, hardwareAddress = None, depot = None, description = "", copyProperties = True ):
|
---|
146 |
|
---|
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)
|
---|
164 |
|
---|
165 | if depot:
|
---|
166 | self.clientSetDepot(dst,depot)
|
---|
167 |
|
---|
168 | if self.debug:
|
---|
169 | pprint( self.getProductOnClient( src ) )
|
---|
170 | self.copyProductOnClient( src, dst )
|
---|
171 | if copyProperties:
|
---|
172 | if self.debug:
|
---|
173 | print "copy product properties"
|
---|
174 | if not depot:
|
---|
175 | # get default Properties from Master Depot Server (OpsiConfigserver)
|
---|
176 | depot = self.getOpsiConfigserverId()
|
---|
177 | self.copyProductPropertyState( src, dst, depot )
|
---|
178 | print "done"
|
---|
179 | return True
|
---|
180 |
|
---|
181 | def getProductOnClient( self, client, attributes = ProductAttributesCopy ):
|
---|
182 | return self.rpc.productOnClient_getHashes( [], { 'clientId': client } )
|
---|
183 |
|
---|
184 | def copyProductOnClient( self, src, dst, attributes = ProductAttributesCopy ):
|
---|
185 | products_src = self.rpc.productOnClient_getHashes( attributes, { 'clientId': src } )
|
---|
186 | products_dst = []
|
---|
187 | for i in products_src:
|
---|
188 | if self.debug:
|
---|
189 | print i['productId']
|
---|
190 | pprint( i )
|
---|
191 | i['clientId'] = dst
|
---|
192 | products_dst.append(i)
|
---|
193 | self.rpc.productOnClient_createObjects( products_dst )
|
---|
194 | if self.debug:
|
---|
195 | pprint( self.getProductOnClient( dst ) )
|
---|
196 |
|
---|
197 |
|
---|
198 | def getProductPropertyState( self, client, attributes = [] ):
|
---|
199 | return self.rpc.productPropertyState_getHashes( [], { 'objectId': client } )
|
---|
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 = []
|
---|
207 | productProperties_src = self.getProductPropertyState( src, attributes )
|
---|
208 | productProperties_dst = []
|
---|
209 | for i in productProperties_src:
|
---|
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)
|
---|
224 | self.rpc.productPropertyState_createObjects( productProperties_dst )
|
---|
225 | if self.debug:
|
---|
226 | pprint( self.getProductPropertyState( dst ) )
|
---|
227 |
|
---|
228 |
|
---|
229 | def getClientProductProperty( self, client, product ):
|
---|
230 | return self.rpc.getProductProperties_hash( product, [ client ] )
|
---|
231 |
|
---|
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 |
|
---|
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" )
|
---|
269 |
|
---|
270 |
|
---|
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 ):
|
---|
296 | try:
|
---|
297 | fd.write( "#\n" )
|
---|
298 | fd.write( "# automatically generated at {0}\n".format( time.asctime() ) )
|
---|
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 |
|
---|
305 |
|
---|
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 )
|
---|
312 |
|
---|
313 | file_opsi_jobs = open('opsi-jobs-generated.conf', 'w')
|
---|
314 | self.write_config_file_header( file_opsi_jobs )
|
---|
315 | except BaseException as e:
|
---|
316 | self.logger.exception( "failed to create files" )
|
---|
317 | return False
|
---|
318 | for client in clientsWithBacula:
|
---|
319 | clientId = client['clientId']
|
---|
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 |
|
---|
336 | if __name__ == '__main__':
|
---|
337 | logging.basicConfig(format='%(message)s')
|
---|
338 | logger = logging.getLogger(__name__)
|
---|
339 | logger.setLevel(logging.INFO)
|
---|
340 |
|
---|
341 | parser = argparse.ArgumentParser(description='Command line tool for OPSI configuration.', epilog=HelpEpilog )
|
---|
342 |
|
---|
343 | parser.add_argument( '--debug', action='store_true', help="enable debugging output" )
|
---|
344 |
|
---|
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 |
|
---|
354 | subparsers = parser.add_subparsers(title='subcommands',
|
---|
355 | description='valid subcommands',
|
---|
356 | help='additional help',
|
---|
357 | dest='subcommand' )
|
---|
358 |
|
---|
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" )
|
---|
361 |
|
---|
362 | parser_copy = subparsers.add_parser('copy', help='copy/create a opsi client from a template opsi client')
|
---|
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" )
|
---|
368 | #parser_copy.add_argument( '--no-properties', action='store_false', help="don't copy product properties" )
|
---|
369 |
|
---|
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' )
|
---|
375 |
|
---|
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" )
|
---|
378 |
|
---|
379 | parser_info = subparsers.add_parser('info', help='print information about a opsi client' )
|
---|
380 | parser_info.add_argument( 'src', help="opsi client" )
|
---|
381 |
|
---|
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 |
|
---|
390 | args = parser.parse_args()
|
---|
391 |
|
---|
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" )
|
---|
406 |
|
---|
407 | opsi=OpsiRpc( url, args.debug )
|
---|
408 |
|
---|
409 | result = True
|
---|
410 |
|
---|
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
|
---|
434 |
|
---|
435 | if args.debug: print result
|
---|
436 |
|
---|
437 | if result:
|
---|
438 | exit(0)
|
---|
439 | else:
|
---|
440 | exit(1)
|
---|