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

Last change on this file since 1117 was 1117, checked in by joergs, on Nov 9, 2012 at 5:40:28 PM

added function update client

  • Property svn:executable set to *
File size: 16.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"
[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
216 def write_client_conf( self, fd, client, properties ):
217 #Client {
218 #Name = ting-fd
219 #Address = ting.dass-it
220 #FDPort = 9102
221 #Catalog = MyCatalog
222 #Password = "D5w2V5w6B8a9H5Z"
223 #File Retention = 6 months
224 #Job Retention = 6 months
225 #AutoPrune = yes
226 #}
227 params = [ "FDPort", "FileRetention", "JobRetention", "AutoPrune" ]
228 fd.write( "Client {\n" )
229 fd.write( ' Name = "' + properties['filedaemon_full_name'] + '"' + "\n" )
230 fd.write( ' Address = "' + client['clientId'] + '"' + "\n" )
231 # ipAddress: method host_getObjects [] '{"id":client['clientId']}'
232 #print " # Address =", ipAddress
233 fd.write( ' Password = "' + properties['filedaemon_full_password'] + '"' + "\n" )
234 try:
235 catalog = properties['catalog']
236 except KeyError:
237 catalog = "MyCatalog"
238 fd.write( ' Catalog = "' + catalog + '"' + "\n" )
239 for i in params:
240 try:
241 fd.write( ' ' + i + ' = "' + properties[i.lower()] + '"' + "\n" )
242 except KeyError:
243 fd.write( ' # ' + i + " = \n" )
244 fd.write( "}\n")
245 fd.write( "\n" )
[1087]246
[1110]247
[1087]248
249
[1110]250 def write_job_conf( self, fd, client, properties ):
251 #Job {
252 #FileSet = "tingfileset"
253 #Name = "ting"
254 #Client = ting-fd
255 #JobDefs = "LaptopJob"
256 ## Write Bootstrap = "/var/lib/bacula/ting.bsr"
257 #}
258 params = [ "Fileset", "JobDefs" ]
259 fd.write( "Job {" + "\n" )
260 fd.write( ' Name = "' + client['clientId'] + '-job"' + "\n" )
261 fd.write( ' Client = "' + properties['filedaemon_full_name'] + '"' + "\n" )
262 for i in params:
263 fd.write( " " )
264 try:
265 if not properties[i.lower()]:
266 fd.write( "# " )
267 fd.write( i + ' = "' + properties[i.lower()] + '"' + "\n" )
268 except KeyError:
269 fd.write( "# " + i + " = " + "\n" )
270 fd.write( "}" + "\n" )
271 fd.write( "\n" )
272
273
274 def write_config_file_header( self, fd ):
275 try:
276 fd.write( "#\n" )
[1114]277 fd.write( "# automatically generated at {0}\n".format( time.asctime() ) )
[1110]278 fd.write( "#\n\n" )
279 except BaseException as e:
280 self.logger.exception( "failed to create files" )
281 return False
282 return True
283
284
285 def createBaculaConfigFiles( self ):
286 clientsWithBacula=self.getClientsWithProduct( "bacula" )
287 if clientsWithBacula:
288 try:
289 file_opsi_clients = open('opsi-clients-generated.conf', 'w')
290 self.write_config_file_header( file_opsi_clients )
291
292 file_opsi_jobs = open('opsi-jobs-generated.conf', 'w')
293 self.write_config_file_header( file_opsi_jobs )
294 except BaseException as e:
295 self.logger.exception( "failed to create files" )
296 return False
297 for client in clientsWithBacula:
298 clientId = client['clientId']
299 try:
300 clientBaculaProperties=self.getClientProductProperty( clientId, "bacula" )
301 except ValueError as e:
302 self.logger.warn( "%s: no valid information found: %s" %(clientId, e) )
303 else:
304 if clientBaculaProperties:
305 #pprint( clientBaculaProperties )
306 self.write_client_conf( file_opsi_clients, client, clientBaculaProperties )
307 self.write_job_conf( file_opsi_jobs, client, clientBaculaProperties )
308 self.logger.info( "%s: OK" % clientId )
309 else:
310 self.logger.warn( "%s: failed: no product properties defined" %(clientId) )
311 return True
312
313
314
[1047]315if __name__ == '__main__':
[1110]316 logging.basicConfig(format='%(message)s')
317 logger = logging.getLogger(__name__)
318 logger.setLevel(logging.INFO)
319
[1063]320 parser = argparse.ArgumentParser(description='Command line tool for OPSI configuration.', epilog=HelpEpilog )
321
[1047]322 parser.add_argument( '--debug', action='store_true', help="enable debugging output" )
[1028]323
[1110]324 parser_url = parser.add_mutually_exclusive_group(required=True)
325 parser_url.add_argument( '--url', help="OPSI Server JSON-RPC url, in following format: " + UrlJsonRpc )
326
327 parser_url.add_argument( '--server', help="OPSI Server (instead of URL)" )
328 username_default=os.getlogin()
329
330 parser.add_argument( '--username', help="username (instead of URL), default: " + username_default, default=username_default )
331 parser.add_argument( '--password', help="password (instead of URL)" )
332
[1050]333 subparsers = parser.add_subparsers(title='subcommands',
334 description='valid subcommands',
335 help='additional help',
336 dest='subcommand' )
[1047]337
[1050]338 parser_clean = subparsers.add_parser('clean', help='remove all product states from a opsi client' )
339 parser_clean.add_argument( 'src', help="source opsi client to clean" )
[1117]340
[1050]341 parser_copy = subparsers.add_parser('copy', help='copy/create a opsi client from a template opsi client')
342 parser_copy.add_argument( 'src', help="source/template opsi client" )
343 parser_copy.add_argument( 'dst', help="opsi client to be created" )
344 parser_copy.add_argument( '--ip', help="IP address of the new opsi client" )
345 parser_copy.add_argument( '--mac', help="MAC address of the new opsi client" )
346 parser_copy.add_argument( '--depot', help="depot server the new opsi client should be located" )
[1088]347 #parser_copy.add_argument( '--no-properties', action='store_false', help="don't copy product properties" )
[1110]348
349 parser_createBaculaConfigFiles = subparsers.add_parser('createBaculaConfigFiles', help='create Bacula config files for all clients that have bacula installed')
350
351 parser_exists = subparsers.add_parser('exists', help='check, if a opsi clients exists' )
352 parser_exists.add_argument( 'src', help="source opsi client" )
[1050]353
[1110]354 #parser_list = subparsers.add_parser('list', help='list all opsi clients' )
355
356 parser_listClients = subparsers.add_parser('listClients', help='list opsi clients')
357 parser_listClients.add_argument( '--product', help="only list clients, that have product installed" )
358
359 parser_info = subparsers.add_parser('info', help='print information about a opsi client' )
360 parser_info.add_argument( 'src', help="opsi client" )
361
[1117]362 parser_update = subparsers.add_parser('update', help='update/create a opsi client')
363 parser_update.add_argument( 'src', help="opsi client to be created" )
364 parser_update.add_argument( '--ip', help="IP address of the new opsi client" )
365 parser_update.add_argument( '--mac', help="MAC address of the new opsi client" )
366 parser_update.add_argument( '--description', help="IP address of the new opsi client" )
367 parser_update.add_argument( '--notes', help="MAC address of the new opsi client" )
368 parser_update.add_argument( '--depot', help="depot server the new opsi client should be located" )
369
[1047]370 args = parser.parse_args()
371
[1110]372 if args.debug:
373 logger.setLevel(logging.DEBUG)
374
375 url=args.url
376 if (not url):
377 if args.server:
378 account=""
379 if args.username and args.password:
380 account=args.username + ":" + args.password + "@"
381 elif args.username:
382 account=args.username + "@"
383 url="https://" + account + args.server + ":4447/rpc"
384 else:
385 parser.error( "argument --url is required" )
386
387 opsi=OpsiRpc( url, args.debug )
[1050]388
[1051]389 result = True
390
[1110]391 if args.subcommand == "clean":
392 result = opsi.clean( args.src )
393 elif args.subcommand == "copy":
394 result = opsi.copyClient( args.src, args.dst, args.ip, args.mac, args.depot )
395 elif args.subcommand == "createBaculaConfigFiles":
396 result = opsi.createBaculaConfigFiles()
[1051]397 elif args.subcommand == "exists":
[1110]398 result = opsi.exists( args.src )
399 elif args.subcommand == "list":
400 result = opsi.list()
401 elif args.subcommand == "listClients":
402 result = opsi.listClients( args.product )
[1051]403 elif args.subcommand == "info":
[1117]404 result = opsi.info( args.src )
405 elif args.subcommand == "update":
406 result = opsi.updateClient( args.src, None, args.description, args.notes, args.mac, args.ip, args.depot )
[1050]407 else:
408 print "not yet implemented"
409
[1051]410 if args.debug: print result
411
412 if result:
413 exit(0)
414 else:
415 exit(1)
Note: See TracBrowser for help on using the repository browser.