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

Last change on this file since 1062 was 1062, checked in by joergs, 11 years ago

warning about proxy problems

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