root / pykota / trunk / bin / pkturnkey @ 2419

Revision 2419, 7.0 kB (checked in by jerome, 19 years ago)

pkturnkey doesn't need any database access since it uses external commands
to do its job.

  • 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 Turn Key tool
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003, 2004, 2005 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22#
23# $Id$
24#
25#
26
27import sys
28import os
29import pwd
30
31from pykota.tool import Tool, PyKotaToolError, crashed, N_
32
33__doc__ = N_("""pkturnkey v%(__version__)s (c) %(__years__)s %(__author__)s
34
35A turn key tool for PyKota. When launched, this command will initialize
36PyKota's database with all existing print queues and some or all users.
37For now, no prices or limits are set, so printing is fully accounted
38for, but not limited.
39
40command line usage :
41
42  pkturnkey [options]
43
44options :
45
46  -v | --version       Prints pkturnkey version number then exits.
47  -h | --help          Prints this message then exits.
48 
49  -u | --uidmin uid    Only adds users whose uid is greater than or equal to
50                       uid. You can pass an username there as well, and its
51                       uid will be used automatically.
52                       If not set, 0 will be used automatically.
53                       
54  -U | --uidmax uid    Only adds users whose uid is lesser than or equal to
55                       uid. You can pass an username there as well, and its
56                       uid will be used automatically.
57                       If not set, a large value will be used automatically.
58
59examples :                             
60
61  $ pkturnkey --uidmin jerome
62
63  Will initialize PyKota's database will all existing printers and
64  create print accounts for all users whose uid is greater than or
65  equal to jerome's one.
66""")
67       
68class PKTurnKey(Tool) :
69    """A class for an initialization tool."""
70    def listPrinters(self) :
71        """Returns a list of tuples (queuename, deviceuri) for all existing print queues."""
72        self.logdebug("Extracting all print queues.")
73        result = os.popen("lpstat -v", "r")
74        lines = result.readlines()
75        result.close()
76        printers = []
77        for line in lines :
78            (begin, end) = line.split(':', 1)
79            deviceuri = end.strip()
80            queuename = begin.split()[-1]
81            printers.append((queuename, deviceuri))
82        return printers   
83       
84    def listUsers(self, uidmin, uidmax) :   
85        """Returns a list of usernames whose uids are between uidmin and uidmax."""
86        self.logdebug("Extracting all users whose uid is between %s and %s." % (uidmin, uidmax))
87        return [entry[0] for entry in pwd.getpwall() if uidmin <= entry[2] <= uidmax]
88       
89    def createPrinters(self, printers) :   
90        """Creates all printers in PyKota's database."""
91        needswarning = [p[0] for p in printers if p[1].find("cupspykota") == -1]
92        command = "pkprinters --add %s" % " ".join(['"%s"' % p[0] for p in printers])
93        self.logdebug("Launching : %s" % command)
94        os.system(command)
95       
96    def createUsers(self, users) :   
97        """Creates all users in PyKota's database."""
98        command = "edpykota --add --noquota %s" % " ".join(['"%s"' % u for u in users])
99        self.logdebug("Launching : %s" % command)
100        os.system(command)
101       
102    def main(self, names, options) :
103        """Intializes PyKota's database."""
104        if not self.config.isAdmin :
105            raise PyKotaToolError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command."))
106           
107        # TODO : names not used for now   
108        if not names :
109            names = ["*"]
110           
111        if not options["uidmin"] :   
112            self.printInfo(_("System users will have a print account as well !"), "warn")
113            uidmin = 0
114        else :   
115            try :
116                uidmin = int(options["uidmin"])
117            except :   
118                try :
119                    uidmin = pwd.getpwnam(options["uidmin"])[2]
120                except KeyError, msg :   
121                    raise PyKotaToolError, _("Unknown username %s : %s") % (options["uidmin"], msg)
122                   
123        if not options["uidmax"] :   
124            uidmax = sys.maxint
125        else :   
126            try :
127                uidmax = int(options["uidmax"])
128            except :   
129                try :
130                    uidmax = pwd.getpwnam(options["uidmax"])[2]
131                except KeyError, msg :   
132                    raise PyKotaToolError, _("Unknown username %s : %s") % (options["uidmax"], msg)
133                   
134        if uidmin > uidmax :           
135            (uidmin, uidmax) = (uidmax, uidmin)
136        users = self.listUsers(uidmin, uidmax)
137        printers = self.listPrinters()                   
138       
139        print "Please be patient...",
140        sys.stdout.flush()
141        self.createPrinters(printers)
142        self.createUsers(users)
143        print
144        print "Database initialized."
145                   
146                     
147if __name__ == "__main__" : 
148    retcode = 0
149    try :
150        short_options = "hvu:U:"
151        long_options = ["help", "version", "uidmin=", "uidmax="]
152       
153        # Initializes the command line tool
154        manager = PKTurnKey(doc=__doc__)
155        manager.deferredInit()
156       
157        # parse and checks the command line
158        (options, args) = manager.parseCommandline(sys.argv[1:], \
159                                                   short_options, \
160                                                   long_options, \
161                                                   allownothing=1)
162       
163        # sets long options
164        options["help"] = options["h"] or options["help"]
165        options["version"] = options["v"] or options["version"]
166        options["uidmin"] = options["u"] or options["uidmin"]
167        options["uidmax"] = options["U"] or options["uidmax"]
168       
169        if options["help"] :
170            manager.display_usage_and_quit()
171        elif options["version"] :
172            manager.display_version_and_quit()
173        else :
174            retcode = manager.main(args, options)
175    except KeyboardInterrupt :       
176        sys.stderr.write("\nInterrupted with Ctrl+C !\n")
177    except SystemExit :       
178        pass
179    except :
180        try :
181            manager.crashed("pkturnkey failed")
182        except :   
183            crashed("pkturnkey failed")
184        retcode = -1
185
186    try :
187        manager.storage.close()
188    except (TypeError, NameError, AttributeError) :   
189        pass
190       
191    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.