root / pykota / trunk / bin / pkprinters @ 1821

Revision 1821, 12.7 kB (checked in by jalet, 20 years ago)

Now mandates that the user be a PyKota administrator to allow dangerous
command line options. --list is still allowed to mere mortals though.

  • 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# -*- coding: ISO-8859-15 -*-
3
4# PyKota Printers Manager
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 2 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program; if not, write to the Free Software
21# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
22#
23# $Id$
24#
25# $Log$
26# Revision 1.17  2004/10/13 21:40:10  jalet
27# Now mandates that the user be a PyKota administrator to allow dangerous
28# command line options. --list is still allowed to mere mortals though.
29#
30# Revision 1.16  2004/10/11 22:53:05  jalet
31# Postponed string interpolation to help message's output method
32#
33# Revision 1.15  2004/10/11 12:49:06  jalet
34# Renders help translatable
35#
36# Revision 1.14  2004/07/19 22:37:13  jalet
37# pykosd is now a very good tool
38#
39# Revision 1.13  2004/07/01 19:56:41  jalet
40# Better dispatching of error messages
41#
42# Revision 1.12  2004/07/01 17:45:47  jalet
43# Added code to handle the description field for printers
44#
45# Revision 1.11  2004/06/18 13:34:48  jalet
46# Now all tracebacks include PyKota's version number
47#
48# Revision 1.10  2004/06/07 18:43:40  jalet
49# Fixed over-verbose exits when displaying help or version number
50#
51# Revision 1.9  2004/06/03 21:50:34  jalet
52# Improved error logging.
53# crashrecipient directive added.
54# Now exports the job's size in bytes too.
55#
56# Revision 1.8  2004/05/06 20:30:24  jalet
57# Added --skipexisting command line option to pkprinters
58#
59# Revision 1.7  2004/05/06 12:51:58  jalet
60# Documentation
61#
62# Revision 1.6  2004/05/06 12:37:29  jalet
63# pkpgcounter : comments
64# pkprinters : when --add is used, existing printers are now skipped.
65#
66# Revision 1.5  2004/04/16 16:52:09  jalet
67# Better formatting
68#
69# Revision 1.4  2004/04/16 16:47:57  jalet
70# pkprinters now accept the --list command line option
71#
72# Revision 1.3  2004/02/04 13:24:41  jalet
73# pkprinters can now remove printers from printers groups.
74#
75# Revision 1.2  2004/02/04 12:52:37  jalet
76# pkprinters' help
77#
78# Revision 1.1  2004/02/04 11:16:59  jalet
79# pkprinters command line tool added.
80#
81#
82#
83
84import os
85import sys
86import pwd
87
88from pykota.tool import PyKotaTool, PyKotaToolError, crashed, N_
89
90__doc__ = N_("""pkprinters v%s (c) 2003-2004 C@LL - Conseil Internet & Logiciels Libres
91A Printers Manager for PyKota.
92
93command line usage :
94
95  pkprinters [options] printer1 printer2 printer3 ... printerN
96
97options :
98
99  -v | --version       Prints pkprinters's version number then exits.
100  -h | --help          Prints this message then exits.
101 
102  -a | --add           Adds printers if they don't exist on the Quota
103                       Storage Server. If they exist, they are modified
104                       unless -s|--skipexisting is also used.
105                       
106  -d | --delete        Deletes printers from the quota storage.
107 
108  -D | --description   Adds a textual description to printers.
109                       
110  -c | --charge p[,j]  Sets the price per page and per job to charge.
111                       Job price is optional.
112                       If both are to be set, separate them with a comma.
113                       Floating point and negative values are allowed.
114 
115  -g | --groups pg1[,pg2...] Adds or Remove the printer(s) to the printer
116                       groups pg1, pg2, etc... which must already exist.
117                       A printer group is just like a normal printer,
118                       only that it is usually unknown from the printing
119                       system. Create printer groups exactly the same
120                       way that you create printers, then add other
121                       printers to them with this option.
122                       Accounting is done on a printer and on all
123                       the printer groups it belongs to, quota checking
124                       is done on a printer and on all the printer groups
125                       it belongs to.
126                       If the --remove option below is not used, the
127                       default action is to add printers to the specified
128                       printer groups.
129                       
130  -l | --list          List informations about the printer(s) and the
131                       printers groups it is a member of.
132                       
133  -r | --remove        In combination with the --groups option above,                       
134                       remove printers from the specified printers groups.
135                       
136  -s | --skipexisting  In combination with the --add option above, tells
137                       pkprinters to not modify existing printers.
138 
139  printer1 through printerN can contain wildcards if the --add option
140  is not set.
141 
142examples :                             
143
144  $ pkprinters --add -D "HP Printer" --charge 0.05,0.1 hp2100 hp2200 hp8000
145 
146  Will create three printers named hp2100, hp2200 and hp8000.
147  Their price per page will be set at 0.05 unit, and their price
148  per job will be set at 0.1 unit. Units are in your own currency,
149  or whatever you want them to mean.
150  All of their descriptions will be set to the string "HP Printer".
151  If any of these printers already exists, it will also be modified
152  unless the -s|--skipexisting command line option is also used.
153           
154  $ pkprinters --delete "*"
155 
156  This will completely delete all printers and associated quota information,
157  as well as their job history. USE WITH CARE !
158 
159  $ pkprinters --groups Laser,HP "hp*"
160 
161  This will put all printers which name matches "hp*" into printers groups
162  Laser and HP, which MUST already exist.
163 
164  $ pkprinters --groups LexMark --remove hp2200
165 
166  This will remove the hp2200 printer from the LexMark printer group.
167 
168This program is free software; you can redistribute it and/or modify
169it under the terms of the GNU General Public License as published by
170the Free Software Foundation; either version 2 of the License, or
171(at your option) any later version.
172
173This program is distributed in the hope that it will be useful,
174but WITHOUT ANY WARRANTY; without even the implied warranty of
175MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
176GNU General Public License for more details.
177
178You should have received a copy of the GNU General Public License
179along with this program; if not, write to the Free Software
180Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
181
182Please e-mail bugs to: %s""")
183       
184class PKPrinters(PyKotaTool) :       
185    """A class for edpykota."""
186    def main(self, names, options) :
187        """Manage printers."""
188        if (not self.config.isAdmin) and (not options["list"]) :
189            raise PyKotaToolError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command."))
190           
191        if options["list"] and not names :
192            names = ["*"]
193           
194        if options["groups"] :       
195            printersgroups = self.storage.getMatchingPrinters(options["groups"])
196            if not printersgroups :
197                raise PyKotaToolError, _("There's no printer matching %s") % " ".join(options["groups"].split(','))
198           
199        if options["charge"] :
200            try :
201                charges = [float(part) for part in options["charge"].split(',', 1)]
202            except ValueError :   
203                raise PyKotaToolError, _("Invalid charge amount value %s") % options["charge"]
204            else :   
205                if len(charges) > 2 :
206                    charges = charges[:2]
207                if len(charges) != 2 :
208                    charges = [charges[0], None]
209                (perpage, perjob) = charges
210               
211        if options["add"] :   
212            printers = []
213            for pname in names :
214                printer = self.storage.getPrinter(pname)
215                if printer.Exists :
216                    if options["skipexisting"] :
217                        self.printInfo(_("Printer %s already exists, skipping.") % printer.Name)
218                    else :   
219                        self.printInfo(_("Printer %s already exists, will be modified.") % printer.Name)
220                        printers.append(printer)
221                else :
222                    if self.isValidName(pname) :
223                        printer = self.storage.addPrinter(pname)
224                        if not printer.Exists :
225                            raise PyKotaToolError, _("Impossible to add printer %s") % pname
226                        else :   
227                            printers.append(printer)
228                    else :   
229                        raise PyKotaToolError, _("Invalid printer name %s") % pname
230        else :       
231            printers = self.storage.getMatchingPrinters(",".join(names))
232            if not printers :
233                raise PyKotaToolError, _("There's no printer matching %s") % " ".join(names)
234                   
235        for printer in printers :       
236            if options["delete"] :
237                printer.delete()
238            elif options["list"] :   
239                parents = ", ".join([p.Name for p in self.storage.getParentPrinters(printer)])
240                if parents : 
241                    parents = "%s %s" % (_("in"), parents)
242                print "%s [%s] (%s + #*%s) %s" % \
243                      (printer.Name, printer.Description, printer.PricePerJob, \
244                       printer.PricePerPage, parents)
245            else :   
246                if options["charge"] :
247                    printer.setPrices(perpage, perjob)   
248                if options["description"] is not None :
249                    printer.setDescription(options["description"].strip())
250                if options["groups"] :   
251                    for pgroup in printersgroups :
252                        if options["remove"] :
253                            pgroup.delPrinterFromGroup(printer)
254                        else :
255                            pgroup.addPrinterToGroup(printer)   
256                     
257if __name__ == "__main__" : 
258    retcode = 0
259    try :
260        short_options = "hvac:D:dg:lrs"
261        long_options = ["help", "version", "add", "charge=", "description=", "delete", "groups=", "list", "remove", "skipexisting"]
262       
263        # Initializes the command line tool
264        manager = PKPrinters(doc=__doc__)
265       
266        # parse and checks the command line
267        (options, args) = manager.parseCommandline(sys.argv[1:], short_options, long_options)
268       
269        # sets long options
270        options["help"] = options["h"] or options["help"]
271        options["version"] = options["v"] or options["version"]
272        options["add"] = options["a"] or options["add"]
273        options["charge"] = options["c"] or options["charge"]
274        options["description"] = options["D"] or options["description"]
275        options["delete"] = options["d"] or options["delete"] 
276        options["groups"] = options["g"] or options["groups"]
277        options["list"] = options["l"] or options["list"]
278        options["remove"] = options["r"] or options["remove"]
279        options["skipexisting"] = options["s"] or options["skipexisting"]
280       
281        if options["help"] :
282            manager.display_usage_and_quit()
283        elif options["version"] :
284            manager.display_version_and_quit()
285        elif (options["delete"] and (options["add"] or options["groups"] or options["charge"] or options["remove"] or options["description"])) \
286           or (options["skipexisting"] and not options["add"]) \
287           or (options["list"] and (options["add"] or options["delete"] or options["groups"] or options["charge"] or options["remove"] or options["description"])) :
288            raise PyKotaToolError, _("incompatible options, see help.")
289        elif options["remove"] and not options["groups"] :   
290            raise PyKotaToolError, _("You have to pass printer groups names on the command line")
291        elif (not args) and (not options["list"]) :   
292            raise PyKotaToolError, _("You have to pass printer names on the command line")
293        else :
294            retcode = manager.main(args, options)
295    except SystemExit :       
296        pass
297    except :
298        try :
299            manager.crashed("pkprinters failed")
300        except :   
301            crashed("pkprinters failed")
302        retcode = -1
303
304    try :
305        manager.storage.close()
306    except (TypeError, NameError, AttributeError) :   
307        pass
308       
309    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.