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

Last change on this file since 1063 was 1063, checked in by joergs, 10 years ago

beautified

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