コード例 #1
0
ファイル: main.py プロジェクト: gonicus/gosa
    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
コード例 #2
0
ファイル: asyncipp.py プロジェクト: Alberto-Beralix/Beralix
    def run (self):
        if self.host == None:
            self.host = cups.getServer ()
        if self.port == None:
            self.port = cups.getPort ()
        if self._encryption == None:
            self._encryption = cups.getEncryption ()

        if self.user:
            cups.setUser (self.user)
        else:
            self.user = cups.getUser ()

        try:
            cups.setPasswordCB2 (self._auth)
        except AttributeError:
            # Requires pycups >= 1.9.47.  Fall back to rubbish API.
            cups.setPasswordCB (self._auth)

        try:
            conn = cups.Connection (host=self.host,
                                    port=self.port,
                                    encryption=self._encryption)
            self._reply (None)
        except RuntimeError, e:
            conn = None
            self._error (e)
コード例 #3
0
 def __init__(self, butterfly):
     cups.setPasswordCB(self.password_response)
     cups.setUser("cups_ctrl")
     self.bad_password = False
     self.IPP_STATUS_CODES = {
         cups.IPP_PRINTER_IDLE: "IDLE",
         cups.IPP_PRINTER_PROCESSING: "PROCESSING",
         cups.IPP_PRINTER_STOPPED: "STOPPED"
     }
コード例 #4
0
ファイル: __init__.py プロジェクト: spaceone/ucs-school
    def printit(self, username, printjob, printer):
        """Print a given document on the given printer

		requests.options = {}
		'username' -- owner of the print job
		'printjob' -- relative filename of the print job
		'printer' -- the printer to use (<hostname>://<printer>)

		return: <PDF document>
		"""

        path = self._get_path(username, printjob)

        try:
            spoolhost, printer = printer.split('://', 1)
        except ValueError:
            raise UMC_Error(_('Invalid printer URI'))

        if not os.path.exists(path):
            raise UMC_Error(
                _('File %r could not be printed as it does not exists (anymore).'
                  ) % (printjob, ))

        MODULE.process('Printing: %s' % path)
        self.pw_callback_bad_password = False
        try:
            cups.setUser(self.username)
            cups.setEncryption(cups.HTTP_ENCRYPT_ALWAYS)
            cups.setPasswordCB(self.pw_callback)
            conn = cups.Connection(spoolhost)
            conn.printFile(printer, path, Printjob.filename2label(printjob),
                           {})
        except RuntimeError:
            raise UMC_Error(
                _('Failed to connect to print server %(printserver)s.') %
                {'printserver': spoolhost})
        except cups.IPPError as (errno, description):
            IPP_AUTHENTICATION_CANCELED = 4096
            description = {
                cups.IPP_NOT_AUTHORIZED: _('No permission to print'),
                IPP_AUTHENTICATION_CANCELED: _('Wrong password'),
            }.get(errno, description)
            raise UMC_Error(
                _('Failed to print on %(printer)s: %(stderr)s (error %(errno)d).'
                  ) % {
                      'printer': printer,
                      'stderr': description,
                      'errno': errno
                  })
コード例 #5
0
    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))
コード例 #6
0
ファイル: test.py プロジェクト: Distrotech/pycups
def test_cups_module ():
	cups.setUser ("root")
	cups.setPasswordCB (callback)
	conn = cups.Connection ()
	printers = list(conn.getPrinters ().keys ())

	if 0:
		print ("Getting cupsd.conf")
		file ("cupsd.conf", "w")
		conn.getFile ("/admin/conf/cupsd.conf", "cupsd.conf")
		print ("Putting cupsd.conf")
		conn.putFile ("/admin/conf/cupsd.conf", "cupsd.conf")

	print ("Getting PPD for %s" % printers[len (printers) - 1])
	f = conn.getPPD (printers[len (printers) - 1])
	ppd = cups.PPD (f)
	ppd.markDefaults ()
	print (ppd.conflicts ())
	groups = ppd.optionGroups
	for group in groups:
		for opt in group.options:
			print (list (map (lambda x: x["text"], opt.choices)))
コード例 #7
0
def test_cups_module():
    cups.setUser("root")
    cups.setPasswordCB(callback)
    conn = cups.Connection()
    printers = list(conn.getPrinters().keys())

    if 0:
        print("Getting cupsd.conf")
        file("cupsd.conf", "w")
        conn.getFile("/admin/conf/cupsd.conf", "cupsd.conf")
        print("Putting cupsd.conf")
        conn.putFile("/admin/conf/cupsd.conf", "cupsd.conf")

    print("Getting PPD for %s" % printers[len(printers) - 1])
    f = conn.getPPD(printers[len(printers) - 1])
    ppd = cups.PPD(f)
    ppd.markDefaults()
    print(ppd.conflicts())
    groups = ppd.optionGroups
    for group in groups:
        for opt in group.options:
            print(list(map(lambda x: x["text"], opt.choices)))
コード例 #8
0
ファイル: asyncipp.py プロジェクト: Alberto-Beralix/Beralix
        debugprint ("Thread exiting")
        self._destroyed = True
        del self._conn # already destroyed
        del self._reply_handler
        del self._error_handler
        del self._auth_handler
        del self._queue
        del self._auth_queue
        del conn

        try:
            cups.setPasswordCB2 (None)
        except AttributeError:
            # Requires pycups >= 1.9.47.  Fall back to rubbish API.
            cups.setPasswordCB (lambda x: '')

    def _auth (self, prompt, conn=None, method=None, resource=None):
        def prompt_auth (prompt):
            gtk.gdk.threads_enter ()
            if conn == None:
                self._auth_handler (prompt, self._conn)
            else:
                self._auth_handler (prompt, self._conn, method, resource)

            gtk.gdk.threads_leave ()
            return False

        if self._auth_handler == None:
            return ""
コード例 #9
0
        dest='directory', help='Directory to create service files',
        metavar='DIRECTORY')
    parser.add_option('-v', '--verbose', action="store_true", dest="verbose",
        help="Print debugging information to STDERR")
    parser.add_option('-p', '--prefix', action="store", type="string",
        dest='prefix', help='Prefix all files with this string', metavar='PREFIX',
        default='AirPrint-')
    parser.add_option('-a', '--admin', action="store_true", dest="adminurl",
        help="Include the printer specified uri as the adminurl")

    (options, args) = parser.parse_args()

    # TODO XXX FIXME -- if cups login required, need to add
    # air=username,password
    from getpass import getpass
    cups.setPasswordCB(getpass)

    if options.directory:
        if not os.path.exists(options.directory):
            os.mkdir(options.directory)

    apg = AirPrintGenerate(
        user=options.username,
        host=options.hostname,
        port=options.port,
        verbose=options.verbose,
        directory=options.directory,
        prefix=options.prefix,
        adminurl=options.adminurl,
    )
コード例 #10
0
    def _perform_authentication (self):
        self._passes += 1

        creds = global_authinfocache.lookup_auth_info (host=self._server, port=self._port)
        if creds != None:
            if (creds[0] != 'root' or self._try_as_root):
                (self._use_user, self._use_password) = creds
            del creds

        debugprint ("Authentication pass: %d" % self._passes)
        if self._passes == 1:
            # Haven't yet tried the operation.  Set the password
            # callback and return > 0 so we try it for the first time.
            self._has_failed = False
            self._forbidden = False
            self._auth_called = False
            self._cancel = False
            self._cannot_auth = False
            self._dialog_shown = False
            cups.setPasswordCB (self._password_callback)
            debugprint ("Authentication: password callback set")
            return 1

        debugprint ("Forbidden: %s" % self._forbidden)
        if not self._has_failed:
            # Tried the operation and it worked.  Return 0 to signal to
            # break out of the loop.
            debugprint ("Authentication: Operation successful")
            return 0

        # Reset failure flag.
        self._has_failed = False

        if self._passes >= 2:
            # Tried the operation without a password and it failed.
            if (self._try_as_root and
                self._user != 'root' and
                (self._server[0] == '/' or self._forbidden)):
                # This is a UNIX domain socket connection so we should
                # not have needed a password (or it is not a UDS but
                # we got an HTTP_FORBIDDEN response), and so the
                # operation must not be something that the current
                # user is authorised to do.  They need to try as root,
                # and supply the password.  However, to get the right
                # prompt, we need to try as root but with no password
                # first.
                debugprint ("Authentication: Try as root")
                self._use_user = '******'
                self._auth_called = False
                try:
                    self._connect (allow_pk=False)
                except RuntimeError:
                    raise cups.IPPError (cups.IPP_SERVICE_UNAVAILABLE,
                                         'server-error-service-unavailable')

                return 1

        if not self._prompt_allowed:
            debugprint ("Authentication: prompting not allowed")
            self._cancel = True
            return 1

        if not self._auth_called:
            # We aren't even getting a chance to supply credentials.
            debugprint ("Authentication: giving up")
            self._cancel = True
            self._cannot_auth = True
            return 1

        # Reset the flag indicating whether we were given an auth callback.
        self._auth_called = False

        # If we're previously prompted, explain why we're prompting again.
        if self._dialog_shown:
            if self._lock:
                self._gui_event.clear ()
                GLib.timeout_add (1, self._show_not_authorized_dialog)
                self._gui_event.wait ()
            else:
                self._show_not_authorized_dialog ()

        if self._lock:
            self._gui_event.clear ()
            GLib.timeout_add (1, self._perform_authentication_with_dialog)
            self._gui_event.wait ()
        else:
            self._perform_authentication_with_dialog ()

        if self._cancel:
            debugprint ("cancelled")
            return -1

        cups.setUser (self._use_user)
        debugprint ("Authentication: Reconnect")
        try:
            self._connect (allow_pk=False)
        except RuntimeError:
            raise cups.IPPError (cups.IPP_SERVICE_UNAVAILABLE,
                                 'server-error-service-unavailable')

        return 1
コード例 #11
0
	def __init__(self):
				
		cups.setUser('admin')
		cups.setPasswordCB(omvGetAdminPw)
		
		self.conn = cups.Connection()
コード例 #12
0
    def _perform_authentication (self):
        self._passes += 1

        creds = global_authinfocache.lookup_auth_info (host=self._server, port=self._port)
        if creds is not None:
            if (creds[0] != 'root' or self._try_as_root):
                (self._use_user, self._use_password) = creds
            del creds

        debugprint ("Authentication pass: %d" % self._passes)
        if self._passes == 1:
            # Haven't yet tried the operation.  Set the password
            # callback and return > 0 so we try it for the first time.
            self._has_failed = False
            self._forbidden = False
            self._auth_called = False
            self._cancel = False
            self._cannot_auth = False
            self._dialog_shown = False
            cups.setPasswordCB (self._password_callback)
            debugprint ("Authentication: password callback set")
            return 1

        debugprint ("Forbidden: %s" % self._forbidden)
        if not self._has_failed:
            # Tried the operation and it worked.  Return 0 to signal to
            # break out of the loop.
            debugprint ("Authentication: Operation successful")
            return 0

        # Reset failure flag.
        self._has_failed = False

        if self._passes >= 2:
            # Tried the operation without a password and it failed.
            if (self._try_as_root and
                self._user != 'root' and
                (self._server[0] == '/' or self._forbidden)):
                # This is a UNIX domain socket connection so we should
                # not have needed a password (or it is not a UDS but
                # we got an HTTP_FORBIDDEN response), and so the
                # operation must not be something that the current
                # user is authorised to do.  They need to try as root,
                # and supply the password.  However, to get the right
                # prompt, we need to try as root but with no password
                # first.
                debugprint ("Authentication: Try as root")
                self._use_user = '******'
                self._auth_called = False
                try:
                    self._connect (allow_pk=False)
                except RuntimeError:
                    raise cups.IPPError (cups.IPP_SERVICE_UNAVAILABLE,
                                         'server-error-service-unavailable')

                return 1

        if not self._prompt_allowed:
            debugprint ("Authentication: prompting not allowed")
            self._cancel = True
            return 1

        if not self._auth_called:
            # We aren't even getting a chance to supply credentials.
            debugprint ("Authentication: giving up")
            self._cancel = True
            self._cannot_auth = True
            return 1

        # Reset the flag indicating whether we were given an auth callback.
        self._auth_called = False

        # If we're previously prompted, explain why we're prompting again.
        if self._dialog_shown:
            if self._lock:
                self._gui_event.clear ()
                GLib.timeout_add (1, self._show_not_authorized_dialog)
                self._gui_event.wait ()
            else:
                self._show_not_authorized_dialog ()

        if self._lock:
            self._gui_event.clear ()
            GLib.timeout_add (1, self._perform_authentication_with_dialog)
            self._gui_event.wait ()
        else:
            self._perform_authentication_with_dialog ()

        if self._cancel:
            debugprint ("cancelled")
            return -1

        cups.setUser (self._use_user)
        debugprint ("Authentication: Reconnect")
        try:
            self._connect (allow_pk=False)
        except RuntimeError:
            raise cups.IPPError (cups.IPP_SERVICE_UNAVAILABLE,
                                 'server-error-service-unavailable')

        return 1
コード例 #13
0
 def __init__(self, butterfly):
     cups.setPasswordCB(self.password_response)
     cups.setUser("cups_ctrl")
     self.bad_password = False
     self.IPP_STATUS_CODES = {cups.IPP_PRINTER_IDLE : "IDLE", cups.IPP_PRINTER_PROCESSING : "PROCESSING", cups.IPP_PRINTER_STOPPED: "STOPPED"}
コード例 #14
0
ファイル: printermanag.py プロジェクト: oegpyg/sysadminbit
 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()
コード例 #15
0
ファイル: printermanag.py プロジェクト: oegpyg/sysadminbit
 def modo_usuario(self):
     cups.setPasswordCB(self.callback)
     self.cups_con = cups.Connection()
コード例 #16
0
     dest='directory', help='Directory to create service files',
     metavar='DIRECTORY')
 parser.add_option('-v', '--verbose', action="store_true", dest="verbose",
     help="Print debugging information to STDERR")
 parser.add_option('-p', '--prefix', action="store", type="string",
     dest='prefix', help='Prefix all files with this string', metavar='PREFIX',
     default='AirPrint-')
 parser.add_option('-a', '--admin', action="store_true", dest="adminurl",
     help="Include the printer specified uri as the adminurl")
 
 (options, args) = parser.parse_args()
 
 # TODO XXX FIXME -- if cups login required, need to add
 # air=username,password
 from getpass import getpass
 cups.setPasswordCB(getpass)
 
 if options.directory:
     if not os.path.exists(options.directory):
         os.mkdir(options.directory)
 
 apg = AirPrintGenerate(
     user=options.username,
     host=options.hostname,
     port=options.port,
     verbose=options.verbose,
     directory=options.directory,
     prefix=options.prefix,
     adminurl=options.adminurl,
 )
 
コード例 #17
0
 def getServerSettings():
     # Fail if auth required.
     cups.setPasswordCB(lambda x: '')
     cups.setServer('')
     c = cups.Connection()
     return c.adminGetServerSettings()
コード例 #18
0
 def getServerSettings ():
     # Fail if auth required.
     cups.setPasswordCB (lambda x: '')
     cups.setServer ('')
     c = cups.Connection ()
     return c.adminGetServerSettings ()
コード例 #19
0
ファイル: authconn.py プロジェクト: KDE/printer-applet
    def _perform_authentication (self):
        self._passes += 1

        debugprint ("Authentication pass: %d" % self._passes)
        if self._passes == 1:
            # Haven't yet tried the operation.  Set the password
            # callback and return > 0 so we try it for the first time.
            self._has_failed = False
            self._forbidden = False
            self._auth_called = False
            self._cancel = False
            cups.setPasswordCB (self._password_callback)
            debugprint ("Authentication: password callback set")
            return 1

        if not self._has_failed:
            # Tried the operation and it worked.  Return 0 to signal to
            # break out of the loop.
            debugprint ("Authentication: Operation successful")
            return 0

        # Reset failure flag.
        self._has_failed = False

        if self._passes == 2:
            # Tried the operation without a password and it failed.
            if (self._try_as_root and
                self._user != 'root' and
                (self._server[0] == '/' or self._forbidden)):
                # This is a UNIX domain socket connection so we should
                # not have needed a password (or it is not a UDS but
                # we got an HTTP_FORBIDDEN response), and so the
                # operation must not be something that the current
                # user is authorised to do.  They need to try as root,
                # and supply the password.  However, to get the right
                # prompt, we need to try as root but with no password
                # first.
                debugprint ("Authentication: Try as root")
                self._use_user = '******'
                self._auth_called = False
                self._connect ()
                return 1

        if not self._prompt_allowed:
            debugprint ("Authentication: prompting not allowed")
            self._cancel = True
            return 1

        if not self._auth_called:
            # We aren't even getting a chance to supply credentials.
            debugprint ("Authentication: giving up")
            self._cancel = True
            return 1

        # Reset the flag indicating whether we were given an auth callback.
        self._auth_called = False

        # Prompt.
        """FIXME port dialogue
        d = AuthDialog (parent=self._parent)
        d.set_prompt (self._prompt)
        d.set_auth_info ([self._use_user, ''])
        d.field_grab_focus ('password')
        response = d.run ()
        d.hide ()
        """
        response = False

        #if response == gtk.RESPONSE_CANCEL:
        if response:
            self._cancel = True
            return -1

        (self._use_user,
         self._use_password) = d.get_auth_info ()

        cups.setUser (self._use_user)
        debugprint ("Authentication: Reconnect")
        self._connect ()

        return 1