#! /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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # $Id$ # # import sys import os from pykota.tool import Tool, PyKotaToolError, crashed, N_ try : import pysnmp except ImportError : hasSNMP = 0 else : hasSNMP = 1 __doc__ = N_("""pkhint v%s (c) %s %s 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(Tool) : """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 + ')' accounter = 'hardware(pjl)' configuration.append((printer, accounter)) else : configuration.append((printer, "software()")) else : configuration.append((printer, "software()")) 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__) manager.deferredInit() (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 KeyboardInterrupt : sys.stderr.write("\nInterrupted with Ctrl+C !\n") except SystemExit : pass except : try : manager.crashed("pkhint failed") except : crashed("pkhint failed") retcode = -1 sys.exit(retcode)