def get_printers_list(self, ip="localhost", port=631): printer_list = [] try: import cups except ImportError: frappe.throw( _("""This feature can not be used as dependencies are missing. Please contact your system manager to enable this by installing pycups!""") ) return try: cups.setServer(self.server_ip) cups.setPort(self.port) conn = cups.Connection() printers = conn.getPrinters() for printer_id, printer in printers.items(): printer_list.append({ "value": printer_id, "label": printer["printer-make-and-model"] }) except RuntimeError: frappe.throw(_("Failed to connect to server")) except frappe.ValidationError: frappe.throw(_("Failed to connect to server")) return printer_list
def __init__(self, parent=None, try_as_root=True, lock=False, host=None, port=None, encryption=None): if host != None: cups.setServer(host) if port != None: cups.setPort(port) if encryption != None: cups.setEncryption(encryption) self._use_password = '' self._parent = parent self._try_as_root = try_as_root self._use_user = cups.getUser() self._server = cups.getServer() self._port = cups.getPort() self._encryption = cups.getEncryption() self._prompt_allowed = True self._operation_stack = [] self._lock = lock self._gui_event = threading.Event() self._connect()
def print_by_server(doctype, name, print_format=None, doc=None, no_letterhead=0): print_settings = frappe.get_doc("Print Settings") try: import cups except ImportError: frappe.throw("You need to install pycups to use this feature!") return try: cups.setServer(print_settings.server_ip) cups.setPort(print_settings.port) conn = cups.Connection() output = PdfFileWriter() output = frappe.get_print(doctype, name, print_format, doc=doc, no_letterhead=no_letterhead, as_pdf = True, output = output) file = os.path.join("/", "tmp", "frappe-pdf-{0}.pdf".format(frappe.generate_hash())) output.write(open(file,"wb")) conn.printFile(print_settings.printer_name,file , name, {}) except IOError as e: if ("ContentNotFoundError" in e.message or "ContentOperationNotPermittedError" in e.message or "UnknownContentError" in e.message or "RemoteHostClosedError" in e.message): frappe.throw(_("PDF generation failed")) except cups.IPPError: frappe.throw(_("Printing failed")) finally: cleanup(file,{})
def serve(self): try: server = self.env.config.get("cups.server") port = self.env.config.get("cups.port") user = self.env.config.get("cups.user") password = self.env.config.get("cups.password") encryption_policy = getattr(cups, "HTTP_ENCRYPT_%s" % self.env.config.get("cups.encryption-policy", default="IF_REQUESTED").upper()) if server is not None: cups.setServer(server) if port is not None: cups.setPort(int(port)) if user is not None: cups.setUser(user) if encryption_policy is not None: cups.setEncryption(encryption_policy) if password is not None: def pw_callback(prompt): return password cups.setPasswordCB(pw_callback) self.client = cups.Connection() sched = PluginRegistry.getInstance("SchedulerService").getScheduler() sched.add_interval_job(self.__gc, minutes=60, tag='_internal', jobstore="ram") sched.add_interval_job(self.__update_printer_list, minutes=30, tag='_internal', jobstore="ram") except RuntimeError as e: self.log.error(str(e)) self.client = None
def getippqueue( dev, queue, depth ): name = dev.rfind ( '/' ) name = dev[ name + 1: ] dev = dev[ 6: ] e = dev.find( ':' ) if e == -1: e = dev.find( '/' ) host = dev[ :e ] cups.setServer( host ) try: c = cups.Connection () printers = c.getPrinters () classes = c.getClasses () except RuntimeError: # Failed to connect. return except cups.IPPError as e: if e == cups.IPP_OPERATION_NOT_SUPPORTED: # CUPS-Get-Printers not supported so not a CUPS server. printers = {} classes = {} else: return queue = c.getPrinterAttributes( name ) dev = queue[ 'device-uri' ] getqueue( name, queue, host, depth + 1, printers, classes )
def handle(self, *args, **options): cups.setServer(settings.CUPS_SERVER) c = cups.Connection() printers = c.getPrinters() for name, printer in printers.iteritems(): inv_printer = Printer.objects.get_or_create(name=name)[0] inv_printer.update_data_from_cups()
def __init__ (self, parent=None, try_as_root=True, lock=False, host=None, port=None, encryption=None): if host != None: cups.setServer (host) if port != None: cups.setPort (port) if encryption != None: cups.setEncryption (encryption) self._use_password = '' self._parent = parent self._try_as_root = try_as_root self._use_user = cups.getUser () self._server = cups.getServer () self._port = cups.getPort() self._encryption = cups.getEncryption () self._prompt_allowed = True self._operation_stack = [] self._lock = lock self._gui_event = threading.Event () creds = global_authinfocache.lookup_auth_info (host=host, port=port) if creds != None: if (creds[0] != 'root' or try_as_root): (self._use_user, self._use_password) = creds del creds self._connect ()
def collect(self): """Collects the metrics from cups """ start = time.time() self._setup_empty_prometheus_metrics() cups.setServer(self.host) cups.setPort(self.port) cups.setUser(self.user) try: conn = cups.Connection() printers = conn.getPrinters() self._prometheus_metrics['printersNum'].add_metric([], len(printers)) self._getPrinterStatus(printers) self._getJobData(conn) self._prometheus_metrics['cupsUp'].add_metric([], 1) except Exception as e: self._prometheus_metrics['cupsUp'].add_metric([], 0) print(e) duration = time.time() - start self._prometheus_metrics['scrape_duration_seconds'].add_metric( [], duration) for metric in self._prometheus_metrics.values(): yield metric
def display(self): self.answers = {} cups.setServer('') parent = self.troubleshooter.get_window() try: c = self.timedop(cups.Connection, parent=parent).run() printers = self.timedop(c.getPrinters, parent=parent).run() if len(printers) == 0: return False for name, printer in printers.iteritems(): if printer.get('printer-is-shared', False): break attr = self.timedop(c.getPrinterAttributes, args=(name, ), parent=parent).run() except RuntimeError: return False except cups.IPPError: return False if not printer.get('printer-is-shared', False): return False if attr.get('server-is-sharing-printers', True): # server-is-sharing-printers is in CUPS 1.4 return False return True
def print_by_server(doctype, name, print_format=None, doc=None, no_letterhead=0): print_settings = frappe.get_doc("Print Settings") try: import cups except ImportError: frappe.throw(_("You need to install pycups to use this feature!")) return try: cups.setServer(print_settings.server_ip) cups.setPort(print_settings.port) conn = cups.Connection() output = PdfFileWriter() output = frappe.get_print(doctype, name, print_format, doc=doc, no_letterhead=no_letterhead, as_pdf = True, output = output) file = os.path.join("/", "tmp", "frappe-pdf-{0}.pdf".format(frappe.generate_hash())) output.write(open(file,"wb")) conn.printFile(print_settings.printer_name,file , name, {}) except IOError as e: if ("ContentNotFoundError" in e.message or "ContentOperationNotPermittedError" in e.message or "UnknownContentError" in e.message or "RemoteHostClosedError" in e.message): frappe.throw(_("PDF generation failed")) except cups.IPPError: frappe.throw(_("Printing failed")) finally: cleanup(file,{})
def display (self): self.answers = {} cups.setServer ('') parent = self.troubleshooter.get_window () try: c = self.timedop (cups.Connection, parent=parent).run () printers = self.timedop (c.getPrinters, parent=parent).run () if len (printers) == 0: return False for name, printer in printers.iteritems (): if printer.get ('printer-is-shared', False): break attr = self.timedop (c.getPrinterAttributes, args=(name,), parent=parent).run () except RuntimeError: return False except cups.IPPError: return False if not printer.get ('printer-is-shared', False): return False if attr.get ('server-is-sharing-printers', True): # server-is-sharing-printers is in CUPS 1.4 return False return True
def getippqueue(dev, queue, depth): name = dev.rfind('/') name = dev[name + 1:] dev = dev[6:] e = dev.find(':') if e == -1: e = dev.find('/') host = dev[:e] cups.setServer(host) try: c = cups.Connection() printers = c.getPrinters() classes = c.getClasses() except RuntimeError: # Failed to connect. return except cups.IPPError as e: if e == cups.IPP_OPERATION_NOT_SUPPORTED: # CUPS-Get-Printers not supported so not a CUPS server. printers = {} classes = {} else: return queue = c.getPrinterAttributes(name) dev = queue['device-uri'] getqueue(name, queue, host, depth + 1, printers, classes)
def getPrinterInfo(server, self): cups.setServer(server) #cups.setUser(user) conn = cups.Connection() printers = conn.getPrinters() for printer in printers: print printer, printers[printer]["device-uri"]
def get(self, request, *args, **kwargs): cups.setServer(CUPS_IP) cups_instance = cups.Connection() try: items = cups_instance.getJobs(requested_attributes=["job-id", "job-media-sheets-completed", "time-at-creation"]) except: return HttpResponse("error") for key in items: items[key]["time-at-creation"] = datetime.datetime.fromtimestamp(items[key]["time-at-creation"]).isoformat() return HttpResponse(json.dumps(items), content_type="application/json")
def __init__(self, bus=None, my_jobs=True, specific_dests=None, monitor_jobs=True, host=None, port=None, encryption=None): GObject.GObject.__init__(self) self.my_jobs = my_jobs self.specific_dests = specific_dests self.monitor_jobs = monitor_jobs self.jobs = {} self.printer_state_reasons = {} self.printers = set() self.process_pending_events = True self.fetch_jobs_timer = None self.cups_connection_in_error = False if host: cups.setServer(host) if port: cups.setPort(port) if encryption: cups.setEncryption(encryption) self.user = cups.getUser() self.host = cups.getServer() self.port = cups.getPort() self.encryption = cups.getEncryption() self.ppdcache = ppdcache.PPDCache(host=self.host, port=self.port, encryption=self.encryption) self.which_jobs = "not-completed" self.reasons_seen = {} self.connecting_timers = {} self.still_connecting = set() self.connecting_to_device = {} self.received_any_dbus_signals = False self.update_timer = None if bus is None: try: bus = dbus.SystemBus() except dbus.exceptions.DBusException: # System bus not running. pass self.bus = bus if bus is not None: bus.add_signal_receiver(self.handle_dbus_signal, path=self.DBUS_PATH, dbus_interface=self.DBUS_IFACE) self.sub_id = -1
def gethost(host=None, depth=0): if host: cups.setServer(host) else: host = "localhost" c = cups.Connection() printers = c.getPrinters() classes = c.getClasses() indent = do_indent(depth) for name, queue in printers.items(): getqueue(name, queue, host, depth, printers, classes)
def gethost (host=None, depth=0): if host: cups.setServer (host) else: host = "localhost" c = cups.Connection () printers = c.getPrinters () classes = c.getClasses () indent = do_indent(depth) for name, queue in printers.items (): getqueue (name, queue, host, depth, printers, classes)
def display (self): model = Gtk.ListStore (str, str, str, GObject.TYPE_PYOBJECT) self.treeview.set_model (model) iter = model.append (None) model.set (iter, 0, _("Not listed"), 1, '', 2, '', 3, NotListed) parent = self.troubleshooter.get_window () try: cups.setServer ('') c = self.timedop (cups.Connection, parent=parent).run () dests = self.timedop (c.getDests, parent=parent).run () printers = None dests_list = [] for (name, instance), dest in dests.iteritems (): if name == None: continue if instance != None: queue = "%s/%s" % (name, instance) else: queue = name if printers == None: printers = self.timedop (c.getPrinters, parent=parent).run () if not printers.has_key (name): info = _("Unknown") location = _("Unknown") else: printer = printers[name] info = printer.get('printer-info', _("Unknown")) location = printer.get('printer-location', _("Unknown")) dests_list.append ((queue, location, info, dest)) dests_list.sort (lambda x, y: cmp (x[0], y[0])) for queue, location, info, dest in dests_list: iter = model.append (None) model.set (iter, 0, queue, 1, location, 2, info, 3, dest) except cups.HTTPError: pass except cups.IPPError: pass except RuntimeError: pass return True
def display (self): model = gtk.ListStore (gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_PYOBJECT) self.treeview.set_model (model) iter = model.append (None) model.set (iter, 0, _("Not listed"), 1, '', 2, '', 3, None) parent = self.troubleshooter.get_window () try: cups.setServer ('') c = self.timedop (cups.Connection, parent=parent).run () dests = self.timedop (c.getDests, parent=parent).run () printers = None dests_list = [] for (name, instance), dest in dests.iteritems (): if name == None: continue if instance != None: queue = "%s/%s" % (name, instance) else: queue = name if printers == None: printers = self.timedop (c.getPrinters, parent=parent).run () if not printers.has_key (name): info = _("Unknown") location = _("Unknown") else: printer = printers[name] info = printer.get('printer-info', _("Unknown")) location = printer.get('printer-location', _("Unknown")) dests_list.append ((queue, location, info, dest)) dests_list.sort (lambda x, y: cmp (x[0], y[0])) for queue, location, info, dest in dests_list: iter = model.append (None) model.set (iter, 0, queue, 1, location, 2, info, 3, dest) except cups.HTTPError: pass except cups.IPPError: pass except RuntimeError: pass return True
def gethost(host=None, depth=0): # print "entro aqui" if not host: host = "localhost" cups.setServer(host) c = cups.Connection() printers = c.getPrinters() do_indent(depth) lista_impresoras = [] for name, queue in printers.iteritems(): getqueue(name, queue, host, depth, printers, classes) lista_impresoras.append(name) return lista_impresoras
def gethost(host=None, depth=0): # print "entro aqui" if not host: host = "localhost" cups.setServer(host) c = cups.Connection() printers = c.getPrinters() indent = do_indent(depth) lista_impresoras = [] for name, queue in printers.iteritems(): getqueue(name, queue, host, depth, printers, classes) lista_impresoras.append(name) return lista_impresoras
def __init__(self, bus=None, my_jobs=True, specific_dests=None, monitor_jobs=True, host=None, port=None, encryption=None): GObject.GObject.__init__ (self) self.my_jobs = my_jobs self.specific_dests = specific_dests self.monitor_jobs = monitor_jobs self.jobs = {} self.printer_state_reasons = {} self.printers = set() self.process_pending_events = True self.fetch_jobs_timer = None self.cups_connection_in_error = False if host: cups.setServer (host) if port: cups.setPort (port) if encryption: cups.setEncryption (encryption) self.user = cups.getUser () self.host = cups.getServer () self.port = cups.getPort () self.encryption = cups.getEncryption () self.ppdcache = ppdcache.PPDCache (host=self.host, port=self.port, encryption=self.encryption) self.which_jobs = "not-completed" self.reasons_seen = {} self.connecting_timers = {} self.still_connecting = set() self.connecting_to_device = {} self.received_any_dbus_signals = False self.update_timer = None if bus is None: try: bus = dbus.SystemBus () except dbus.exceptions.DBusException: # System bus not running. pass self.bus = bus if bus is not None: bus.add_signal_receiver (self.handle_dbus_signal, path=self.DBUS_PATH, dbus_interface=self.DBUS_IFACE) self.sub_id = -1
def _connect (self): cups.setUser (self._use_user) cups.setServer (self._server) cups.setPort (self._port) self._connection = cups.Connection () self._user = self._use_user debugprint ("Connected as user %s" % self._user) methodtype = type (self._connection.getPrinters) for fname in dir (self._connection): if fname[0] == '_': continue fn = getattr (self._connection, fname) if type (fn) != methodtype: continue setattr (self, fname, self._make_binding (fname, fn))
def create(cls, printer=None, server="", port=0, user=""): """Return a handle to print using a connection to the (local) CUPS server, if available.""" try: import cups except ImportError: return cups.setServer(server or "") cups.setPort(port or 0) cups.setUser(user or "") try: c = cups.Connection() except RuntimeError: return h = cls(c, printer) if h.printer().printerName() in c.getPrinters(): return h
def get_printers( host = None, depth = 0 ) : if not host: try: host = settings.HOST except: host = "localhost" msg = "OK" try: cups.setServer( host ) except: print( "cupstree/get_printers( )" ) type, value, tb = exc_info() msg = "cups.setServer() for host %s failed" % host print( "%s\n" % msg ) return { "msg" : msg, "list" : [] } printers = None classes = None indent = None msg = "OK" try: c = cups.Connection() printers = c.getPrinters () classes = c.getClasses () indent = do_indent( depth ) except: print( "cupstree/get_printers( )" ) type, value, tb = exc_info() msg = "cups.Connection() for host %s failed" % host print( "%s\n" % msg ) return { "msg" : msg, "list" : [] } printer_list = [] try: for ( name, queue ) in iteritems( printers ): printer_dict = getqueue( name, queue, host, depth, printers, classes ) printer_list.append( printer_dict ) except: print( "cupstree/get_printers( )" ) type, value, tb = exc_info() msg = "cups getqueue for host %s failed" % host print( "%s\n" % msg ) return { "msg" : msg, "list" : printer_list }
def get_printers(self,ip="localhost",port=631): printer_list = [] try: import cups except ImportError: frappe.throw("You need to install pycups to use this feature!") return try: cups.setServer(self.server_ip) cups.setPort(self.port) conn = cups.Connection() printers = conn.getPrinters() printer_list = printers.keys() except RuntimeError: frappe.throw(_("Failed to connect to server")) except ValidationError: frappe.throw(_("Failed to connect to server")) return printer_list
def get_printers(self, ip="localhost", port=631): printer_list = [] try: import cups except ImportError: frappe.throw(_("You need to install pycups to use this feature!")) return try: cups.setServer(self.server_ip) cups.setPort(self.port) conn = cups.Connection() printers = conn.getPrinters() printer_list = printers.keys() except RuntimeError: frappe.throw(_("Failed to connect to server")) except frappe.ValidationError: frappe.throw(_("Failed to connect to server")) return printer_list
def print_label(label_file, name): printerName = PRINTER_NAME if os.environ.get('WEB_USER') in REMOTES: settings = REMOTES[os.environ['WEB_USER']] if 'host' not in settings: settings['host'] = os.environ.get('WEB_REMOTE_IP') if settings['host'] == '::1': settings['host'] = '127.0.0.1' if 'username' in settings: cups.setUser(settings['username']) debug('connecting to remote cups %s' % settings['host']) cups.setServer(settings['host']) conn = cups.Connection(settings['host']) if 'printer' in settings: printerName = settings['printer'] else: conn = cups.Connection() printer = printerName or conn.getDefault() debug('print_label connection done') conn.printFile(printer, label_file.name, name, {}) debug('print_label print job sent')
def start(self): self._cpt = 0 if not cups_module: print( '/!\\ ERROR /!\\: the PrinterTarget has been disabled because python-cups module is not installed' ) return False if not self._target_ip: print('/!\\ ERROR /!\\: the PrinterTarget IP has not been set') return False if self._target_port is None: self._target_port = 631 cups.setServer(self._target_ip) cups.setPort(self._target_port) self.__connection = cups.Connection() try: printers = self.__connection.getPrinters() except cups.IPPError as err: print('CUPS Server Errror: ', err) return False if self._printer_name is not None: try: params = printers[self._printer_name] except: print("Printer '%s' is not connected to CUPS server!" % self._printer_name) return False else: self._printer_name, params = printers.popitem() print("\nDevice-URI: %s\nPrinter Name: %s" % (params["device-uri"], self._printer_name)) return True
def __init__(self, parent=None, try_as_root=True, lock=False, host=None, port=None, encryption=None): if host != None: cups.setServer(host) if port != None: cups.setPort(port) if encryption != None: cups.setEncryption(encryption) self._use_password = "" self._parent = parent self._try_as_root = try_as_root self._use_user = cups.getUser() self._server = cups.getServer() self._port = cups.getPort() self._encryption = cups.getEncryption() self._prompt_allowed = True self._operation_stack = [] self._lock = lock self._gui_event = threading.Event() self._connect()
def serve(self): try: server = self.env.config.get("cups.server") port = self.env.config.get("cups.port") user = self.env.config.get("cups.user") password = self.env.config.get("cups.password") encryption_policy = getattr( cups, "HTTP_ENCRYPT_%s" % self.env.config.get( "cups.encryption-policy", default="IF_REQUESTED").upper()) if server is not None: cups.setServer(server) if port is not None: cups.setPort(int(port)) if user is not None: cups.setUser(user) if encryption_policy is not None: cups.setEncryption(encryption_policy) if password is not None: def pw_callback(prompt): return password cups.setPasswordCB(pw_callback) self.client = cups.Connection() sched = PluginRegistry.getInstance( "SchedulerService").getScheduler() sched.add_interval_job(self.__gc, minutes=60, tag='_internal', jobstore="ram") sched.add_interval_job(self.__update_printer_list, minutes=30, tag='_internal', jobstore="ram") except RuntimeError as e: self.log.error(str(e))
def main(): global c, f, p c = None f = None p = None # test for directory existance uppath = __UPLOADS__ + "sample.txt" uppath = os.path.dirname(uppath) if not os.path.exists(uppath): print "making directories at " + uppath os.makedirs(uppath) temppath = __TMP__ + "sample.txt" temppath = os.path.dirname(temppath) if not os.path.exists(temppath): print "making directories at " + temppath os.makedirs(temppath) cups.setServer("localhost") application = Application() application.listen(8080, '0.0.0.0') tornado.ioloop.IOLoop.instance().start()
def getippqueue(dev, queue, depth): # print "entro en el metodo: getippqueue" name = dev.rfind('/') name = dev[name + 1:] dev = dev[6:] e = dev.find(':') if e == -1: e = dev.find('/') host = dev[:e] cups.setServer(host) try: c = cups.Connection() printers = c.getPrinters() except RuntimeError: # Failed to connect. return except cups.IPPError, e: if e == cups.IPP_OPERATION_NOT_SUPPORTED: # CUPS-Get-Printers not supported so not a CUPS server. printers = {} classes = {} else: return
class Printer(models.Model): name = models.CharField(max_length=255, unique=True) location = models.CharField(max_length=255, blank=True) uri = models.CharField(max_length=255, blank=True) model = models.CharField(max_length=255, blank=True) asset_tag = models.CharField(max_length=255, blank=True) toner_levels = models.CharField(max_length=1024, blank=True) connection = models.CharField(max_length=1024, blank=True, null=True) cups.setServer(settings.CUPS_SERVER) c = cups.Connection() def update_data_from_cups(self): try: all_data = c.getPrinterAttributes(name=self.name) except: # Renew connection c = cups.Connection() all_data = c.getPrinterAttributes(name=self.name) self.location = all_data.get('printer-location', '') self.uri = all_data.get('printer-uri-supported', '') self.model = all_data.get('printer-make-and-model', '') self.connection = all_data.get('device-uri', '') marker_names = all_data.get('marker-names', '') marker_levels = all_data.get('marker-levels', '') if marker_names and marker_levels: toner_txt = '' # I've never seen this used. #toner_high_level = all_data.get('toner_high_level', '') for name, level in zip(marker_names, marker_levels): # A value of -1 indicates the level is unavailable, -2 indicates unknown, and -3 indicates the level is unknown but has not yet reached capacity if level != -1 and level != -2: if level == -3: level = "Not at capacity" toner_txt += '%s: %s, ' % ( name, level, ) self.toner_levels = toner_txt[:-2] self.save() @property def state(self): try: state = self.c.getPrinterAttributes(name=self.name, requested_attributes=[ 'printer-state' ])['printer-state'] except: try: c = cups.Connection() state = self.c.getPrinterAttributes(name=self.name, requested_attributes=[ 'printer-state' ])['printer-state'] except: return "Can't connect" if state == 3: return "Idle" elif state == 4: return "Printing" elif state == 5: return "Stopped" else: return state @property def state_reason(self): try: state_reasons = self.c.getPrinterAttributes( name=self.name, requested_attributes=['printer-state-reasons' ])['printer-state-reasons'] txt = '' for reason in state_reasons: txt += '%s, ' % (reason, ) return txt[:-2] except: c = cups.Connection()
def getServerSettings (): # Fail if auth required. cups.setPasswordCB (lambda x: '') cups.setServer ('') c = cups.Connection () return c.adminGetServerSettings ()
import argparse import cups parser = argparse.ArgumentParser(description='List CUPS jobs on remote print server') parser.add_argument('-l', '--limit', type=int, default=10, help='Number of jobs to return') parser.add_argument('status', choices=['completed', 'not-completed', 'all'], help='CUPS Job Status') parser.add_argument('server', nargs='+', help='Print Server') args = parser.parse_args() # Placeholder to track if we already printed printed = None for server in args.server: # Only print a blank line when multiple servers are queried if printed: print() printed = True cups.setServer(server) conn = cups.Connection() jobs = conn.getJobs(which_jobs=args.status, limit=args.limit) print('Jobs on server: {0}'.format(server)) print(' {0:<10} {1:<18} {2}'.format('USER', 'HOST', 'JOB')) for job in jobs: print(' {0:<10} {1:<18} {2}'.format( jobs[job]['job-originating-user-name'], jobs[job]['job-originating-host-name'], jobs[job]['job-name']))
while not camera_connected: try: camera = gp.Camera() camera.init() camera_connected = True except gp.GPhoto2Error: print( "Camera not detected, please turn camera on. Attempting to connect again in 3 seconds..." ) pg.time.wait(3000) #initialize button button = Button(25) #initialzie printer cups.setServer("localhost") success = False while not success: try: conn = cups.Connection() printers = conn.getPrinters() if DEBUG: for printer in printers: print("{} - {}".format(printer, printers[printer]['device-uri'])) PRINTER_NAME = printer print("Main printer: {}".format(PRINTER_NAME)) success = True except RuntimeError: print("Not able to connect to printer, trying again in one second...")
def display (self): self.answers = {} answers = self.troubleshooter.answers if not answers['cups_queue_listed']: return False parent = self.troubleshooter.get_window () name = answers['cups_queue'] tmpf = None try: cups.setServer ('') self.op = TimedOperation (cups.Connection, parent=parent) c = self.op.run () self.op = TimedOperation (c.getPPD, args=(name,), parent=parent) tmpf = self.op.run () except RuntimeError: return False except cups.IPPError: return False self.install_button.hide () title = None text = None try: ppd = cups.PPD (tmpf) self.answers['cups_printer_ppd_valid'] = True def options (options_list): o = {} for option in options_list: o[option.keyword] = option.defchoice return o defaults = {} for group in ppd.optionGroups: g = options (group.options) for subgroup in group.subgroups: g[subgroup.name] = options (subgroup.options) defaults[group.name] = g self.answers['cups_printer_ppd_defaults'] = defaults except RuntimeError: title = _("Invalid PPD File") self.answers['cups_printer_ppd_valid'] = False try: self.op = TimedSubprocess (parent=parent, args=['cupstestppd', '-rvv', tmpf], close_fds=True, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result = self.op.run () self.answers['cupstestppd_output'] = result text = _("The PPD file for printer '%s' does not conform " "to the specification. " "Possible reason follows:") % name text += '\n' + reduce (lambda x, y: x + '\n' + y, result[0]) except OSError: # Perhaps cupstestppd is not in the path. text = _("There is a problem with the PPD file for " "printer '%s'.") % name if tmpf: os.unlink (tmpf) if title == None and not answers['cups_printer_remote']: (pkgs, exes) = cupshelpers.missingPackagesAndExecutables (ppd) self.answers['missing_pkgs_and_exes'] = (pkgs, exes) if len (pkgs) > 0 or len (exes) > 0: title = _("Missing Printer Driver") if len (pkgs) > 0: try: self.packagekit = installpackage.PackageKit () except: pkgs = [] if len (pkgs) > 0: self.package = pkgs[0] text = _("Printer '%s' requires the %s package but it " "is not currently installed.") % (name, self.package) self.install_button.show () else: text = _("Printer '%s' requires the '%s' program but it " "is not currently installed.") % (name, (exes + pkgs)[0]) if title != None: self.label.set_markup ('<span weight="bold" size="larger">' + title + '</span>\n\n' + text) return title != None
def __init__(self, usuario, clave): self.gpp = clave cups.setServer(settings.CUPS_SERVER.get('maestro')) cups.setUser(usuario)
def __init__(self): cups.setServer("localhost") self.printer_name = self.load_default_printer() self.conn = ""
def get(self, request, *args, **kwargs): cups.setServer(CUPS_IP) cups_instance = cups.Connection() items = cups_instance.getPrinters() return HttpResponse(json.dumps(items), content_type="application/json")
def display(self): self.answers = {} answers = self.troubleshooter.answers if not answers['cups_queue_listed']: return False parent = self.troubleshooter.get_window() name = answers['cups_queue'] tmpf = None try: cups.setServer('') self.op = TimedOperation(cups.Connection, parent=parent) c = self.op.run() self.op = TimedOperation(c.getPPD, args=(name, ), parent=parent) tmpf = self.op.run() except RuntimeError: return False except cups.IPPError: return False self.install_button.hide() title = None text = None try: ppd = cups.PPD(tmpf) self.answers['cups_printer_ppd_valid'] = True def options(options_list): o = {} for option in options_list: o[option.keyword] = option.defchoice return o defaults = {} for group in ppd.optionGroups: g = options(group.options) for subgroup in group.subgroups: g[subgroup.name] = options(subgroup.options) defaults[group.name] = g self.answers['cups_printer_ppd_defaults'] = defaults except RuntimeError: title = _("Invalid PPD File") self.answers['cups_printer_ppd_valid'] = False try: self.op = TimedSubprocess(parent=parent, args=['cupstestppd', '-rvv', tmpf], close_fds=True, stdin=file("/dev/null"), stdout=subprocess.PIPE, stderr=subprocess.PIPE) result = self.op.run() self.answers['cupstestppd_output'] = result text = _("The PPD file for printer '%s' does not conform " "to the specification. " "Possible reason follows:") % name text += '\n' + reduce(lambda x, y: x + '\n' + y, result[0]) except OSError: # Perhaps cupstestppd is not in the path. text = _("There is a problem with the PPD file for " "printer '%s'.") % name if tmpf: os.unlink(tmpf) if title == None and not answers['cups_printer_remote']: (pkgs, exes) = cupshelpers.missingPackagesAndExecutables(ppd) self.answers['missing_pkgs_and_exes'] = (pkgs, exes) if len(pkgs) > 0 or len(exes) > 0: title = _("Missing Printer Driver") if len(pkgs) > 0: try: self.packagekit = installpackage.PackageKit() except: pkgs = [] if len(pkgs) > 0: self.package = pkgs[0] text = _( "Printer '%s' requires the %s package but it " "is not currently installed.") % (name, self.package) self.install_button.show() else: text = _( "Printer '%s' requires the '%s' program but it " "is not currently installed.") % (name, (exes + pkgs)[0]) if title != None: self.label.set_markup('<span weight="bold" size="larger">' + title + '</span>\n\n' + text) return title != None
def modo_admin(self): cups.setServer(settings.CUPS_SERVER.get('maestro')) cups.setUser(settings.CUPS_ADMIN[0]) cups.setPasswordCB(callback_admin) self.cups_con = cups.Connection()
def display (self): # Collect information useful for the various checks. self.answers = {} answers = self.troubleshooter.answers if not answers['cups_queue_listed']: return False name = answers['cups_queue'] parent = self.troubleshooter.get_window () # Find out if this is a printer or a class. try: cups.setServer ('') c = TimedOperation (cups.Connection, parent=parent).run () printers = TimedOperation (c.getPrinters, parent=parent).run () if printers.has_key (name): self.answers['is_cups_class'] = False queue = printers[name] self.answers['cups_printer_dict'] = queue else: self.answers['is_cups_class'] = True classes = TimedOperation (c.getClasses, parent=parent).run () queue = classes[name] self.answers['cups_class_dict'] = queue attrs = TimedOperation (c.getPrinterAttributes, (name,), parent=parent).run () self.answers['local_cups_queue_attributes'] = attrs except: pass if self.answers.has_key ('cups_printer_dict'): cups_printer_dict = self.answers['cups_printer_dict'] uri = cups_printer_dict['device-uri'] (scheme, rest) = urllib.splittype (uri) self.answers['cups_device_uri_scheme'] = scheme if scheme in ["ipp", "http", "https"]: (hostport, rest) = urllib.splithost (rest) (host, port) = urllib.splitnport (hostport, defport=631) self.answers['remote_server_name'] = host self.answers['remote_server_port'] = port elif scheme == "smb": u = smburi.SMBURI (uri) (group, host, share, user, password) = u.separate () new_environ = os.environ.copy() new_environ['LC_ALL'] = "C" if group: args = ["nmblookup", "-W", group, host] else: args = ["nmblookup", host] try: p = TimedSubprocess (parent=parent, timeout=5000, args=args, env=new_environ, close_fds=True, stdin=file("/dev/null"), stdout=subprocess.PIPE, stderr=subprocess.PIPE) result = p.run () self.answers['nmblookup_output'] = result for line in result[0]: if line.startswith ("querying"): continue spc = line.find (' ') if (spc != -1 and not line[spc:].startswith (" failed ")): # Remember the IP address. self.answers['remote_server_name'] = line[:spc] break except OSError: # Problem executing command. pass elif scheme == "hp": new_environ = os.environ.copy() new_environ['LC_ALL'] = "C" new_environ['DISPLAY'] = "" try: p = TimedSubprocess (parent=parent, timeout=3000, args=["hp-info", "-d" + uri], close_fds=True, env=new_environ, stdin=file("/dev/null"), stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.answers['hplip_output'] = p.run () except OSError: # Problem executing command. pass r = cups_printer_dict['printer-type'] & cups.CUPS_PRINTER_REMOTE self.answers['cups_printer_remote'] = (r != 0) return False
def post(self, request, *args, **kwargs): cups.setServer(CUPS_IP) cups_instance = cups.Connection() cups_instance.cancelJob(int(kwargs.get("job_id"))) # This does not return any useful information return HttpResponse("ok")
def getServerSettings(): # Fail if auth required. cups.setPasswordCB(lambda x: '') cups.setServer('') c = cups.Connection() return c.adminGetServerSettings()
def display (self): troubleshooter = self.troubleshooter try: queue = troubleshooter.answers['cups_queue'] except KeyError: return False parent = self.troubleshooter.get_window () cups.setServer ('') self.op = TimedOperation (cups.Connection, parent=parent) c = self.op.run () self.op = TimedOperation (c.getPrinterAttributes, args=(queue,), parent=parent) dict = self.op.run () the_ppdcache = ppdcache.PPDCache () text = '' state_message = dict['printer-state-message'] if state_message: text += _("The printer's state message is: '%s'.") % state_message text += '\n\n' state_reasons_list = dict['printer-state-reasons'] if type (state_reasons_list) == unicode: state_reasons_list = [state_reasons_list] self.state_message = state_message self.state_reasons = state_reasons_list human_readable_errors = [] human_readable_warnings = [] for reason in state_reasons_list: if reason == "none": continue r = statereason.StateReason (queue, reason, the_ppdcache) (title, description) = r.get_description () level = r.get_level () if level == statereason.StateReason.ERROR: human_readable_errors.append (description) elif level == statereason.StateReason.WARNING: human_readable_warnings.append (description) if human_readable_errors: text += _("Errors are listed below:") + '\n' text += reduce (lambda x, y: x + "\n" + y, human_readable_errors) text += '\n\n' if human_readable_warnings: text += _("Warnings are listed below:") + '\n' text += reduce (lambda x, y: x + "\n" + y, human_readable_warnings) self.label.set_text (text) if (state_message == '' and len (human_readable_errors) == 0 and len (human_readable_warnings) == 0): return False # If this screen has been show before, don't show it again if # nothing changed. if troubleshooter.answers.has_key ('printer-state-message'): if (troubleshooter.answers['printer-state-message'] == self.state_message and troubleshooter.answers['printer-state-reasons'] == self.state_reasons): return False return True
if value['printer-state-reasons'][0] != 'none': printersStatus.labels( printer=key, model=value['printer-make-and-model'], status=value['printer-state-reasons'][0]).set(0) else: printersStatus.labels(printer=key, model=value['printer-make-and-model'], status='happy').set(1) if __name__ == '__main__': # Start up the server to expose the metrics. start_http_server(args.listen_port) cups.setServer(args.cups_host) cups.setPort(args.cups_port) cups.setUser(args.cups_user) while True: try: conn = cups.Connection() printers = getPrinterData(conn) getJobData(conn) getPrinterStatus(printers) cupsUp.set(1) except Exception as e: cupsUp.set(0) print(e) time.sleep(5)
def display (self): troubleshooter = self.troubleshooter try: queue = troubleshooter.answers['cups_queue'] except KeyError: return False parent = self.troubleshooter.get_window () cups.setServer ('') self.op = TimedOperation (cups.Connection, parent=parent) c = self.op.run () self.op = TimedOperation (c.getPrinterAttributes, args=(queue,), parent=parent) dict = self.op.run () the_ppdcache = ppdcache.PPDCache () text = '' state_message = dict['printer-state-message'] if state_message: text += _("The printer's state message is: '%s'.") % state_message text += '\n\n' state_reasons_list = dict['printer-state-reasons'] if type (state_reasons_list) == str: state_reasons_list = [state_reasons_list] self.state_message = state_message self.state_reasons = state_reasons_list human_readable_errors = [] human_readable_warnings = [] for reason in state_reasons_list: if reason == "none": continue r = statereason.StateReason (queue, reason, the_ppdcache) (title, description) = r.get_description () level = r.get_level () if level == statereason.StateReason.ERROR: human_readable_errors.append (description) elif level == statereason.StateReason.WARNING: human_readable_warnings.append (description) if human_readable_errors: text += _("Errors are listed below:") + '\n' text += reduce (lambda x, y: x + "\n" + y, human_readable_errors) text += '\n\n' if human_readable_warnings: text += _("Warnings are listed below:") + '\n' text += reduce (lambda x, y: x + "\n" + y, human_readable_warnings) self.label.set_text (text) if (state_message == '' and len (human_readable_errors) == 0 and len (human_readable_warnings) == 0): return False # If this screen has been show before, don't show it again if # nothing changed. if 'printer-state-message' in troubleshooter.answers: if (troubleshooter.answers['printer-state-message'] == self.state_message and troubleshooter.answers['printer-state-reasons'] == self.state_reasons): return False return True
import cups cups.setServer("121.248.53.183") cups.setPort(631) # conn = cups.Connection() # print cups.getServer(),cups.getPort() # conn.printFile('xerox','123.pdf','test',{}) # printers = conn.getPrinters () # for printer in printers: # print printer, printers[printer]["device-uri"] conn = cups.Connection() printers = conn.getPrinters() printer_name = printers.keys()[0] print printer_name conn.printFile(printer_name, "1234.pdf", "Photo Booth", {"page-ranges": "3-4", "sides": "two-sided-long-edges"}) # conn.printFile(printer_name, BPicture, "Photo Booth",{"copies": "2"})