source: opsi/server/dass-opsi-tools/usr/bin/opsi-client @ 1055

Last change on this file since 1055 was 1055, checked in by joergs, 9 years ago

added standard header

  • Property svn:executable set to *
File size: 6.9 KB
Line 
1#!/usr/bin/env python
2
3"""ospi-client: performs operation for opsi clients on opsi server via JSON-RPC."""
4
5__author__ = "Jörg Steffens"
6__copyright__ = "Copyright 2012, dass IT GmbH"
7__license__ = "GPL"
8__version__ = "1.0"
9__email__ = "joerg.steffens@dass-it.de"
10
11#
12# Skript, dass ein OPSI-Rechner-Eintrag kopiert.
13# D.h. die Produkte, Anforderung.
14# Ggf. optional Stand und ggf. Versionsnummer
15# Ggf. optional ProductProperties
16#
17
18#self.command("opsi-admin -d method host_createOpsiClient "+ \
19        #computername + " null " + "\\'"+description+"\\'" + \
20        #" \\'created by dassadmin\\' " + mac_address + " " + \
21        #ip_address)
22#self.command("opsi-admin -d method configState_create clientconfig.depot.id " + \
23        #computername + " " + depotName)                       
24                       
25import argparse
26import jsonrpc
27from pprint import pprint
28
29UrlJsonRpc="https://<USERNAME>:<PASSWORD>@opsi:4447/rpc"
30
31class OpsiRpc:
32   
33    ProductAttributesCopy = ['actionRequest','actionResult','installationStatus','packageVersion','productVersion']
34   
35    def __init__(self, urlJsonRpc, debug=False ):
36        self.debug=debug
37        self.urlJsonRpc=urlJsonRpc
38        self.rpc=jsonrpc.ServiceProxy(self.urlJsonRpc)
39       
40    def dump(self):
41        print self.urlJsonRpc
42        print self.rpc.getClientIds_list()
43
44    def list(self):
45        return self.rpc.getClientIds_list()
46       
47    def exists(self, src):
48        return len( self.rpc.host_getObjects( [], {"id":src} ) ) == 1
49       
50    def info(self, src):
51        if not self.exists( src ):
52            print "failed: opsi client", src, "does not exist"
53            return False
54        print src + ":"
55        host = self.rpc.host_getHashes( [], {"id":src} )[0]
56        print "  IP:", host["ipAddress"]
57        print "  MAC:", host["hardwareAddress"]
58        print "  inventory:", host["inventoryNumber"]
59        print "  last seen:", host["lastSeen"]
60        print "  notes:", host["notes"]
61       
62        print "  products:"
63        products = self.getProductOnClient( src, [] )
64        for i in products:
65            print "    " + i['productId'] + ":"
66            print "      " + i['installationStatus'], "(",
67            if i['actionRequest']:
68                print i['actionRequest'],
69                if i['actionProgress']:
70                    print i['actionProgress'],
71            print ")"
72            print "      ",
73            pprint( i, indent=8 )
74        return True
75
76    def clean(self, src):
77        if not self.exists( src ):
78            return False
79        products = self.rpc.productOnClient_getObjects( [], { 'clientId': src } )
80        self.rpc.productOnClient_deleteObjects( products )
81        if self.debug:
82            pprint( self.getProductOnClient( src ) )
83        return True
84       
85    def copyClient( self, src, dst, ipAddress = None, hardwareAddress = None, depot = None ):
86   
87        print "create/update", dst, "from template", src + ":",
88        #method host_createOpsiClient id *opsiHostKey *description *notes *hardwareAddress *ipAddress *inventoryNumber *oneTimePassword *created *lastSeen
89        #id=dst
90        opsiHostKey=None
91        description=""
92        notes="copy of " + src
93        self.rpc.host_createOpsiClient( dst, opsiHostKey, description, notes, hardwareAddress, ipAddress )
94        if depot:
95            self.rpc.configState_create( "clientconfig.depot.id", dst, depot )       
96        if self.debug:
97            pprint( self.getProductOnClient( src ) )
98        self.copyProductOnClient( src, dst )
99        # TODO:
100        #  copy product properties:
101        #  opsiCallClientBaculaProperties=[ "method", "getProductProperties_hash", "bacula" ]
102        print "done"
103        return True
104
105       
106    def getProductOnClient( self, client, attributes = ProductAttributesCopy ):
107        #pprint( self.rpc.productOnClient_getObjects( [], { 'clientId': client } ) )
108        #pprint( self.rpc.productOnClient_getHashes( attributes, { 'clientId': client } ) )
109        return self.rpc.productOnClient_getHashes( [], { 'clientId': client } )
110       
111    def copyProductOnClient( self, src, dst, attributes = ProductAttributesCopy ):
112        products = self.rpc.productOnClient_getHashes( attributes, { 'clientId': src } )
113        for i in products:
114            if self.debug:
115                print i['productId']
116                pprint( i )
117            i['clientId'] = dst
118            self.rpc.productOnClient_createObjects( i )
119        if self.debug:
120            pprint( self.getProductOnClient( dst ) )
121       
122
123
124if __name__ == '__main__':
125    parser = argparse.ArgumentParser(description='Command line tool for OPSI configuration.')
126    parser.add_argument( '--debug', action='store_true', help="enable debugging output" )
127    #parser.add_argument( '--verbose', type=bool, help="add debugging output" )
128    parser.add_argument( '--url', help="OPSI Server JSON-RPC url, normally https://<username>:<password>@<OPSI-SERVER>:4447/rpc" )
129
130    subparsers = parser.add_subparsers(title='subcommands',
131        description='valid subcommands',
132        help='additional help',
133        dest='subcommand' )
134
135    parser_list = subparsers.add_parser('list', help='list all opsi clients' )
136
137    parser_exists = subparsers.add_parser('exists', help='check, if a opsi clients exists' )
138    parser_exists.add_argument( 'src', help="source opsi client" )
139
140    parser_info = subparsers.add_parser('info', help='print information about a opsi client' )
141    parser_info.add_argument( 'src', help="opsi client" )
142       
143    parser_clean = subparsers.add_parser('clean', help='remove all product states from a opsi client' )
144    parser_clean.add_argument( 'src', help="source opsi client to clean" )
145               
146    parser_copy = subparsers.add_parser('copy', help='copy/create a opsi client from a template opsi client')   
147    parser_copy.add_argument( 'src', help="source/template opsi client" )
148    parser_copy.add_argument( 'dst', help="opsi client to be created" )
149    parser_copy.add_argument( '--ip', help="IP address of the new opsi client" )
150    parser_copy.add_argument( '--mac', help="MAC address of the new opsi client" )
151    parser_copy.add_argument( '--depot', help="depot server the new opsi client should be located" )
152   
153    args = parser.parse_args()
154   
155   
156    urlJsonRpc = UrlJsonRpc
157    if args.url:
158        urlJsonRpc = args.url
159   
160    opsi=OpsiRpc( urlJsonRpc, args.debug )
161   
162    result = True
163
164    if args.subcommand == "list":
165        print( "\n".join( opsi.list() ) )
166    elif args.subcommand == "exists":
167        result = opsi.exists( args.src )
168    elif args.subcommand == "info":
169        result = opsi.info( args.src )       
170    elif args.subcommand == "clean":
171        result = opsi.clean( args.src )
172    elif args.subcommand == "copy":
173        result = opsi.copyClient( args.src, args.dst, args.ip, args.mac, args.depot )
174    else:
175        print "not yet implemented"
176
177    if args.debug: print result   
178       
179    if result:
180        exit(0)
181    else:
182        exit(1)
Note: See TracBrowser for help on using the repository browser.