#! /usr/bin/env python # -*- coding: ISO-8859-15 -*- # PyKota tool to hint for printer accounters # # PyKota - Print Quotas for CUPS and LPRng # # (c) 2003, 2004, 2005 Jerome Alet # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. # # $Id$ # # $Log$ # Revision 1.22 2005/01/17 08:44:23 jalet # Modified copyright years # # Revision 1.21 2004/10/13 08:26:06 jalet # Doesn't suggest hardware(snmp) anymore if the command used was not snmpget. # This caused problem when snmpwalk was successful but not snmpget for example # # Revision 1.20 2004/10/13 08:09:19 jalet # More complete PATH. # pkhint doesn't use absolute path to search for helper commands anymore. # # Revision 1.19 2004/10/11 22:53:05 jalet # Postponed string interpolation to help message's output method # # Revision 1.18 2004/10/11 12:49:06 jalet # Renders help translatable # # Revision 1.17 2004/09/23 19:29:36 jalet # If SNMP accounting is possible, pkhint now suggests to use the internal # SNMP handling instead of the external one. No real test is done for now, # though. # # Revision 1.16 2004/07/27 21:50:29 jalet # Small fix for %(port)s thanks to rpinheiro # # Revision 1.15 2004/07/20 22:19:45 jalet # Sanitized a bit + use of gettext # # Revision 1.14 2004/07/01 19:56:40 jalet # Better dispatching of error messages # # Revision 1.13 2004/06/29 07:55:18 jalet # Doesn't output the warning message when --help or --version is asked # # Revision 1.12 2004/06/29 07:53:11 jalet # Improved pkhint # # Revision 1.11 2004/06/18 13:34:48 jalet # Now all tracebacks include PyKota's version number # # Revision 1.10 2004/06/07 18:43:40 jalet # Fixed over-verbose exits when displaying help or version number # # Revision 1.9 2004/06/03 21:50:34 jalet # Improved error logging. # crashrecipient directive added. # Now exports the job's size in bytes too. # # Revision 1.8 2004/05/18 14:48:47 jalet # Big code changes to completely remove the need for "requester" directives, # jsut use "hardware(... your previous requester directive's content ...)" # # Revision 1.7 2004/05/13 13:59:27 jalet # Code simplifications # # Revision 1.6 2004/03/30 12:59:47 jalet # Fixed path problem # # Revision 1.5 2004/02/09 13:07:06 jalet # Should now be able to handle network + pjl printers # # Revision 1.4 2004/02/09 12:35:19 jalet # De-uglyfication. # Now works with older CUPS (1.14) which don't detect the cupspykota backend but accept it anyway. # # Revision 1.3 2004/02/07 13:56:03 jalet # Help # # Revision 1.2 2004/02/07 13:47:55 jalet # More warnings # # Revision 1.1 2004/02/07 13:45:51 jalet # Preliminary work on the pkhint command # # # import sys import os from pykota.tool import PyKotaTool, PyKotaToolError, crashed, N_ from pykota.config import PyKotaConfigError from pykota.storage import PyKotaStorageError try : import pysnmp except ImportError : hasSNMP = 0 else : hasSNMP = 1 __doc__ = N_("""pkhint v%s (c) 2003, 2004, 2005 C@LL - Conseil Internet & Logiciels Libres A tool to give hints on what accounting method is best for each printer. command line usage : pkhint [options] [printer1 printer2 printer3 ... printerN] /dev/null', \ 'snmpget -v1 -c public -Ov %(printer)s mib-2.43.10.2.1.4.1.1 2>/dev/null | cut -f 2,2 -d " "', \ 'snmpwalk -v 1 -Cc -c public %(printer)s 2>/dev/null | grep mib-2.43.10.2.1.4.1.1 | cut -d " " -f4', \ 'snmpwalk -v 1 -Cc -c public -Ov %(printer)s 2>/dev/null | grep Counter32 | tail -2 | head -1 | cut -d " " -f2', \ ] NETPJLTESTS = [ \ '/usr/share/pykota/pagecount.pl %(printer)s %(port)s 2>/dev/null', \ 'nc -w 2 %(printer)s %(port)s /dev/null | tail -2', \ ] class PKHint(PyKotaTool) : """A class to autodetect the best accounting method for printers.""" def extractPrintersInformation(self) : """Extracts printer information from the printing system. Returns a mapping { queuename : device, ... } """ printers = {} current_printer = None for line in [l.strip() for l in sys.stdin.readlines()] : testline = line.lower() if testline.startswith("/dev/null") deviceslist = [l.strip() for l in inp.readlines()] inp.close() devicestypes = {} for device in deviceslist : (dtype, dname) = device.split() devicestypes[dname] = dtype return devicestypes def searchDeviceType(self, devicestypes, device) : """Returns the device type for current device.""" if device.startswith("cupspykota:") : fulldevice = device[:] device = fulldevice[len("cupspykota:"):] if device.startswith("//") : device = device[2:] for (k, v) in devicestypes.items() : if device.startswith(k) : return v def extractDeviceFromURI(self, device) : """Cleans the device URI to remove any trace of PyKota.""" if device.startswith("cupspykota:") : fulldevice = device[:] device = fulldevice[len("cupspykota:"):] if device.startswith("//") : device = device[2:] try : (backend, destination) = device.split(":", 1) except ValueError : raise PyKotaToolError, _("Invalid DeviceURI : %s") % device while destination.startswith("/") : destination = destination[1:] checkauth = destination.split("@", 1) if len(checkauth) == 2 : destination = checkauth[1] return destination.split("/")[0] def accepts(self, commands, printer, port=None) : """Tries to get the printer's internal page counter via SNMP.""" for command in commands : inp = os.popen(command % locals()) value = inp.readline().strip() inp.close() try : pagecounter = int(value) except : pass else : if port is None : return command else : return command.replace("%(port)s", str(port)) def main(self, args, options) : """Main work is done here.""" os.environ["PATH"] = "%s:/bin:/usr/bin:/usr/local/bin:/opt/bin:/sbin:/usr/sbin" % os.environ.get("PATH", "") sys.stderr.write("BEWARE : This tool doesn't support LPRng's printcap files yet.\n") print _("\nPlease wait while pkhint analyzes your printing system's configuration...") printers = self.extractPrintersInformation() devicestypes = self.extractDevices() # TODO : IT'S CUPS ONLY FOR NOW configuration = [] for (printer, deviceuri) in printers.items() : if self.matchString(printer, args) : devicetype = self.searchDeviceType(devicestypes, deviceuri) device = self.extractDeviceFromURI(deviceuri) if devicetype is None : self.printInfo(_("Unknown device %s for printer %s") % (device, printer)) elif devicetype == "network" : try : hostname, port = device.split(':') except ValueError : hostname = device port = 9100 # TODO : may cause problems with other protocols. snmpcommand = self.accepts(SNMPTESTS, hostname) if snmpcommand is not None : if hasSNMP and snmpcommand.startswith("snmpget ") : # don't do a more complex test, just consider it will work accounter = 'hardware(snmp)' else : accounter = 'hardware(/usr/share/pykota/waitprinter.sh %(printer)s && ' + snmpcommand + ')' configuration.append((printer, accounter)) else : netpjlcommand = self.accepts(NETPJLTESTS, hostname, port) if netpjlcommand is not None : accounter = 'hardware(' + netpjlcommand + ')' configuration.append((printer, accounter)) else : configuration.append((printer, "software(/usr/bin/pkpgcounter)")) else : configuration.append((printer, "software(/usr/bin/pkpgcounter)")) if not configuration : print "\nSorry, pkhint can't help you for now. Please configure PyKota manually." else : print _("\nPut the following lines into your /etc/pykota/pykota.conf file :\n") print _("# BEWARE : if software accounting is suggested, this doesn't mean") print _("# that hardware accounting wouldn't work, this only means that PyKota") print _("# wasn't able to autodetect which hardware accounting method to use.") for (printer, accounter) in configuration : print "[%s]" % printer print "accounter: %s" % accounter print if __name__ == "__main__" : retcode = 0 try : short_options = "hv" long_options = ["help", "version"] # Initializes the command line tool manager = PKHint(doc=__doc__) (options, args) = manager.parseCommandline(sys.argv[1:], short_options, long_options) # sets long options options["help"] = options["h"] or options["help"] options["version"] = options["v"] or options["version"] if options["help"] : manager.display_usage_and_quit() elif options["version"] : manager.display_version_and_quit() else : if not args : args = [ "*" ] retcode = manager.main(args, options) except SystemExit : pass except : try : manager.crashed("pkhint failed") except : crashed("pkhint failed") retcode = -1 try : manager.storage.close() except (TypeError, NameError, AttributeError) : pass sys.exit(retcode)