root / pykota / trunk / bin / edpykota @ 847

Revision 847, 14.7 kB (checked in by jalet, 21 years ago)

Cleaner example.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1#! /usr/bin/env python
2
3# PyKota Print Quota Editor
4#
5# PyKota - Print Quotas for CUPS
6#
7# (c) 2003 Jerome Alet <alet@librelogiciel.com>
8# You're welcome to redistribute this software under the
9# terms of the GNU General Public Licence version 2.0
10# or, at your option, any higher version.
11#
12# You can read the complete GNU GPL in the file COPYING
13# which should come along with this software, or visit
14# the Free Software Foundation's WEB site http://www.fsf.org
15#
16# $Id$
17#
18# $Log$
19# Revision 1.26  2003/03/10 00:11:27  jalet
20# Cleaner example.
21#
22# Revision 1.25  2003/03/09 23:56:21  jalet
23# Option noquota added to do accounting only.
24#
25# Revision 1.24  2003/02/27 23:48:41  jalet
26# Correctly maps PyKota's log levels to syslog log levels
27#
28# Revision 1.23  2003/02/27 22:55:20  jalet
29# WARN log priority doesn't exist.
30#
31# Revision 1.22  2003/02/27 09:37:02  jalet
32# Wildcards seem to work now
33#
34# Revision 1.21  2003/02/27 09:04:46  jalet
35# user and group names can be passed as wildcards if the --add option
36# is not set. The default is to act on all users or groups.
37#
38# Revision 1.20  2003/02/10 12:07:30  jalet
39# Now repykota should output the recorded total page number for each printer too.
40#
41# Revision 1.19  2003/02/09 13:40:29  jalet
42# typo
43#
44# Revision 1.18  2003/02/09 12:56:53  jalet
45# Internationalization begins...
46#
47# Revision 1.17  2003/02/08 22:47:23  jalet
48# Option --reset can now be used without having to use soft and hard limits
49# on the command line.
50#
51# Revision 1.16  2003/02/08 22:39:46  jalet
52# --reset command line option added
53#
54# Revision 1.15  2003/02/08 22:20:01  jalet
55# Clarification on why we don't check with /etc/passwd to see if the user
56# name is valid or not.
57#
58# Revision 1.14  2003/02/08 22:18:15  jalet
59# Now checks user and group names for validity before adding them
60#
61# Revision 1.13  2003/02/08 22:09:02  jalet
62# Only printer was added the first time.
63#
64# Revision 1.12  2003/02/08 21:44:49  jalet
65# Python 2.1 string module doesn't define ascii_letters
66#
67# Revision 1.11  2003/02/08 09:42:44  jalet
68# Better handle wrong or bad command line arguments
69#
70# Revision 1.10  2003/02/08 09:39:20  jalet
71# typos
72#
73# Revision 1.9  2003/02/08 09:38:06  jalet
74# Badly placed test
75#
76# Revision 1.8  2003/02/07 22:53:57  jalet
77# Checks if printer name is valid before adding it
78#
79# Revision 1.7  2003/02/07 22:17:58  jalet
80# Incomplete test
81#
82# Revision 1.6  2003/02/07 22:13:13  jalet
83# Perhaps edpykota is now able to add printers !!! Oh, stupid me !
84#
85# Revision 1.5  2003/02/06 14:49:04  jalet
86# edpykota should be ok now
87#
88# Revision 1.4  2003/02/06 14:28:59  jalet
89# edpykota should be ok, minus some typos
90#
91# Revision 1.3  2003/02/06 10:47:21  jalet
92# Documentation string and command line options didn't match.
93#
94# Revision 1.2  2003/02/06 10:39:23  jalet
95# Preliminary edpykota work.
96#
97# Revision 1.1  2003/02/05 21:41:09  jalet
98# Skeletons added for all command line tools
99#
100#
101#
102
103import sys
104
105from pykota import version
106from pykota.tool import PyKotaTool, PyKotaToolError
107
108__doc__ = """edpykota v%s (C) 2003 C@LL - Conseil Internet & Logiciels Libres
109A Print Quota editor for PyKota.
110
111command line usage :
112
113  edpykota [options] user1 user2 ... userN
114  edpykota [options] group1 group2 ... groupN
115
116options :
117
118  -v | --version       Prints edpykota's version number then exits.
119  -h | --help          Prints this message then exits.
120 
121  -a | --add           Adds users and/or printers if they don't
122                       exist on the Quota Storage Server.
123                       
124  -u | --users         Edit users print quotas, this is the default.
125 
126  -P | --printer p     Edit quotas on printer p only. Actually p can
127                       use wildcards characters to select only
128                       some printers. The default value is *, meaning
129                       all printers.
130 
131  -g | --groups        Edit groups print quotas instead of users.
132                         
133  -p | --prototype u|g Uses user u or group g as a prototype to set
134                       print quotas
135                       
136  -n | --noquota       Doesn't set a quota but only does accounting.
137 
138  -r | --reset         Resets the printed page counter for the user
139                       or group to zero. The life time page counter
140                       is kept unchanged.
141                       
142  -S | --softlimit sl  Sets the quota soft limit to sl pages.                       
143 
144  -H | --hardlimit hl  Sets the quota hard limit to hl pages.
145 
146  user1 through userN and group1 through groupN can use wildcards
147  if the --add option is not set.
148 
149examples :                             
150
151  $ edpykota -p jerome john paul george ringo
152 
153  This will set print quotas for the users john, paul, george and ringo
154  to the same values than user jerome. User jerome must exist.
155 
156  $ edpykota --printer lp -S 50 -H 60 jerome
157 
158  This will set jerome's print quota on the lp printer to a soft limit
159  of 50 pages, and a hard limit of 60 pages. If either user jerome or
160  printer lp doesn't exist on the Quota Storage Server then nothing is done.
161
162  $ edpykota --add --printer lp -S 50 -H 60 jerome
163 
164  Same as above, but if either user jerome or printer lp doesn't exist
165  on the Quota Storage Server they are automatically added.
166  WARNING : the CUPS PPD file for this printer must still be modified
167            manually, as well as pykota's configuration file for a
168            new printer to be managed successfully.
169           
170  $ edpykota -g -S 500 -H 550 financial support           
171 
172  This will set print quota soft limit to 500 pages and hard limit
173  to 550 pages for groups financial and support on all printers.
174 
175  $ edpykota --reset jerome "jo*"
176 
177  This will reset jerome's page counter to zero on all printers, as
178  well as every user whose name begins with 'jo'.
179  Their life time page counter on each printer will be kept unchanged.
180 
181  $ edpykota --printer hpcolor --noquota jerome
182 
183  This will tell PyKota to not limit jerome when printing on the
184  hpcolor printer. All his jobs will be allowed on this printer, but
185  accounting of the pages he prints will still be kept.
186  Print Quotas for jerome on other printers is unchanged.
187
188This program is free software; you can redistribute it and/or modify
189it under the terms of the GNU General Public License as published by
190the Free Software Foundation; either version 2 of the License, or
191(at your option) any later version.
192
193This program is distributed in the hope that it will be useful,
194but WITHOUT ANY WARRANTY; without even the implied warranty of
195MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
196GNU General Public License for more details.
197
198You should have received a copy of the GNU General Public License
199along with this program; if not, write to the Free Software
200Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
201
202Please e-mail bugs to: %s""" % (version.__version__, version.__author__)
203       
204class EdPyKota(PyKotaTool) :       
205    """A class for edpykota."""
206    def main(self, names, options) :
207        """Edit user or group quotas."""
208        printernames = self.storage.getMatchingPrinters(options["printer"])
209        if not printernames :
210            pname = options["printer"]
211            if options["add"] and pname :
212                if self.isValidName(pname) :
213                    self.storage.addPrinter(pname)
214                    printernames = [ (pname, 0) ]
215                else :   
216                    raise PyKotaToolError, _("Invalid printer name %s") % pname
217            else :
218                raise PyKotaToolError, _("There's no printer matching %s") % pname
219        softlimit = hardlimit = None   
220        if options["softlimit"] :
221            try :
222                softlimit = int(options["softlimit"].strip())
223            except ValueError :   
224                raise PyKotaToolError, _("Invalid softlimit value %s.") % options["softlimit"]
225        if options["hardlimit"] :
226            try :
227                hardlimit = int(options["hardlimit"].strip())
228            except ValueError :   
229                raise PyKotaToolError, _("Invalid hardlimit value %s.") % options["hardlimit"]
230        if (softlimit is not None) and (hardlimit is not None) and (hardlimit < softlimit) :       
231            # error, exchange them
232            self.logger.log_message(_("Hard limit %i is less than soft limit %i, values will be exchanged.") % (hardlimit, softlimit))
233            (softlimit, hardlimit) = (hardlimit, softlimit)
234        if not names :   
235            if options["add"] :
236                raise PyKotaToolError, _("You have to pass user names on the command line")
237            else :   
238                names = [ "*" ] # all users
239        for (printer, printerpagecounter) in printernames :
240            if options["prototype"] :
241                if options["users"] :
242                    prototype = self.storage.getUserPQuota(options["prototype"], printer)
243                else :     
244                    prototype = self.storage.getGroupPQuota(options["prototype"], printer)
245                if prototype is None :
246                    self.logger.log_message(_("Prototype %s not found in Quota Storage for printer %s.") % (options["prototype"], printer))
247                    continue    # skip this printer
248                else :   
249                    (softlimit, hardlimit) = (prototype["softlimit"], prototype["hardlimit"])
250            if hardlimit is None :   
251                hardlimit = softlimit
252                self.logger.log_message(_("Undefined hard limit set to soft limit (%s) on printer %s.") % (str(hardlimit), printer))
253            if softlimit is None :   
254                softlimit = hardlimit
255                self.logger.log_message(_("Undefined soft limit set to hard limit (%s) on printer %s.") % (str(softlimit), printer))
256            if (not options["reset"] and not options["noquota"]) and ((hardlimit is None) or (softlimit is None)) :
257                raise PyKotaToolError, _("Both hard and soft limits must be set ! Aborting.")
258            if options["add"] :   
259                allnames = names
260            else :   
261                if options["users"] :   
262                    allnames = self.storage.getPrinterUsers(printer)
263                else :   
264                    allnames = self.storage.getPrinterGroups(printer)
265            for name in [n for n in allnames if self.matchString(n, names)]:
266                if options["users"] :
267                    quota = self.storage.getUserPQuota(name, printer)
268                else :
269                    quota = self.storage.getGroupPQuota(name, printer)
270                if quota is None :
271                    # not found
272                    if options["add"] :
273                        # In case we want to add something, it is crucial
274                        # that we DON'T check with the system accounts files
275                        # like /etc/passwd because users may be defined
276                        # only remotely
277                        if options["users"] :
278                            if self.isValidName(name) :
279                                self.storage.addUserPQuota(name, printer)
280                                quota = self.storage.getUserPQuota(name, printer)
281                            else :   
282                                self.logger.log_message(_("Invalid user name %s") % name)
283                        else :
284                            if self.isValidName(name) :
285                                self.storage.addGroupPQuota(name, printer)
286                                quota = self.storage.getGroupPQuota(name, printer)
287                            else :   
288                                self.logger.log_message(_("Invalid group name %s") % name)
289                if quota is None :     
290                    self.logger.log_message(_("Quota not found for object %s on printer %s.") % (name, printer))
291                else :   
292                    if options["users"] :
293                        if options["noquota"] or ((softlimit is not None) and (hardlimit is not None)) :
294                            self.storage.setUserPQuota(name, printer, softlimit, hardlimit)
295                        if options["reset"] :
296                            self.storage.resetUserPQuota(name, printer)
297                    else :
298                        if options["noquota"] or ((softlimit is not None) and (hardlimit is not None)) :
299                            self.storage.setGroupPQuota(name, printer, softlimit, hardlimit)
300                        if options["reset"] :
301                            self.storage.resetGroupPQuota(name, printer)
302                     
303if __name__ == "__main__" : 
304    try :
305        defaults = { \
306                     "users"  : 1, \
307                     "groups" : 0, \
308                     "printer" : "*", \
309                   }
310        short_options = "vhnaugrp:P:S:H:"
311        long_options = ["help", "version", "noquota", "add", "users", "groups", "reset", "prototype=", "printer=", "softlimit=", "hardlimit="]
312       
313        # Initializes the command line tool
314        editor = EdPyKota(doc=__doc__)
315       
316        # parse and checks the command line
317        (options, args) = editor.parseCommandline(sys.argv[1:], short_options, long_options)
318       
319        # sets long options
320        options["help"] = options["h"] or options["help"]
321        options["version"] = options["v"] or options["version"]
322        options["add"] = options["a"] or options["add"]
323        options["users"] = options["u"] or options["users"] or defaults["users"]
324        options["groups"] = options["g"] or options["groups"] or defaults["groups"]
325        options["prototype"] = options["p"] or options["prototype"]
326        options["printer"] = options["P"] or options["printer"] or defaults["printer"]
327        options["softlimit"] = options["S"] or options["softlimit"]
328        options["hardlimit"] = options["H"] or options["hardlimit"] 
329        options["reset"] = options["r"] or options["reset"] 
330        options["noquota"] = options["n"] or options["noquota"]
331       
332        if options["help"] :
333            editor.display_usage_and_quit()
334        elif options["version"] :
335            editor.display_version_and_quit()
336        elif options["users"] and options["groups"] :   
337            raise PyKotaToolError, _("incompatible options, see help.")
338        elif (options["softlimit"] or options["hardlimit"]) and options["prototype"] :   
339            raise PyKotaToolError, _("incompatible options, see help.")
340        elif options["noquota"] and (options["prototype"] or options["hardlimit"] or options["softlimit"]) :
341            raise PyKotaToolError, _("incompatible options, see help.")
342        elif options["groups"] :   
343            raise PyKotaToolError, _("option --groups is currently not implemented.")
344        else :
345            sys.exit(editor.main(args, options))
346    except PyKotaToolError, msg :           
347        sys.stderr.write("%s\n" % msg)
348        sys.stderr.flush()
349        sys.exit(-1)
Note: See TracBrowser for help on using the browser.