예제 #1
0
    def handle_hplip_updation(self):
        log.debug("handle_hplip_updation upgrade_notify =%d"%(self.user_settings.upgrade_notify))
        path = utils.which('hp-upgrade')
        if self.user_settings.upgrade_notify is False:
            log.debug("upgrade notification is disabled in systray ")
            if path:
                path = os.path.join(path, 'hp-upgrade')
                log.debug("Running hp-upgrade: %s " % (path))
                # this just updates the available version in conf file. But won't notify
                os.spawnlp(os.P_NOWAIT, path, 'hp-upgrade', '--check')
                time.sleep(5)
                try:
                    os.waitpid(0, os.WNOHANG)
                except OSError:
                    pass
            return


        current_time = time.time()

        if int(current_time) > self.user_settings.upgrade_pending_update_time:
            path = utils.which('hp-upgrade')
            if path:
                path = os.path.join(path, 'hp-upgrade')
                log.debug("Running hp-upgrade: %s " % (path))
                os.spawnlp(os.P_NOWAIT, path, 'hp-upgrade', '--notify')
                time.sleep(5)
            else:
                log.error("Unable to find hp-upgrade --notify on PATH.")
        else:
            log.debug("upgrade schedule time is not yet completed. schedule time =%d current time =%d " %(self.user_settings.upgrade_pending_update_time, current_time))
        try:
            os.waitpid(0, os.WNOHANG)
        except OSError:
            pass
예제 #2
0
def restore_loglevels():
    result = False
    cmd = 'cp -f %s %s' % (CUPS_BACKUP_FILE, CUPS_FILE)
    log.debug("Restoring CUPS conf file. cmd=%s" % cmd)
    sts, out = utils.run(cmd)
    if sts == 0:
        cmd = 'rm -f %s' % CUPS_BACKUP_FILE
        log.debug("Removing Temporary file.. cmd=%s" % cmd)
        sts, out = utils.run(cmd)
        if sts != 0:
            log.warn("Failed to remove the Temporary backup file=%s" %
                     CUPS_BACKUP_FILE)
    else:
        log.error("Failed to restore cups config file = %s" % CUPS_FILE)
    log.debug("Restarting CUPS service")

    cmd = None
    if utils.which('service'):
        cmd = os.path.join(utils.which('service'), 'service') + " cups restart"
    elif utils.which('systemctl'):
        cmd = os.path.join(utils.which('systemctl'),
                           'systemctl') + " restart %s.service" % service_name
    elif os.path.exists('/etc/init.d/cups'):
        cmd = "/etc/init.d/cups restart"
    else:
        log.error("service command not found.. Please restart cups manually..")

    if cmd:
        log.debug("CUPS restart cmd = %s" % cmd)
        sts, out = utils.run(cmd)
        if sts == 0:
            result = True

    return result
예제 #3
0
def restore_loglevels():
    result = False
    cmd='cp -f %s %s'%(CUPS_BACKUP_FILE,CUPS_FILE)
    log.debug("Restoring CUPS conf file. cmd=%s"%cmd)
    sts, out = utils.run(cmd)
    if sts == 0:
       cmd='rm -f %s'%CUPS_BACKUP_FILE
       log.debug("Removing Temporary file.. cmd=%s"%cmd)
       sts,out = utils.run(cmd)
       if sts != 0:
            log.warn("Failed to remove the Temporary backup file=%s"%CUPS_BACKUP_FILE)
    else:
       log.error("Failed to restore cups config file = %s"%CUPS_FILE)
    log.debug("Restarting CUPS service")

    cmd=None
    if utils.which('service'):
       cmd = os.path.join(utils.which('service'), 'service')+" cups restart"
    elif utils.which('systemctl'):
       cmd = os.path.join(utils.which('systemctl'), 'systemctl')+" restart %s.service"%service_name
    elif os.path.exists('/etc/init.d/cups'):
       cmd = "/etc/init.d/cups restart"
    else:
       log.error("service command not found.. Please restart cups manually..")

    if cmd:
        log.debug("CUPS restart cmd = %s"%cmd)
        sts,out = utils.run(cmd)
        if sts == 0:
           result = True

    return result
예제 #4
0
def add_group(core):
    result = False
    add_user_to_group = core.get_distro_ver_data('add_user_to_group', '')
    if add_user_to_group:
        usermod = os.path.join(
            utils.which("usermod"),
            "usermod") + " %s %s" % (add_user_to_group, prop.username)
    else:
        usermod = os.path.join(utils.which("usermod"),
                               "usermod") + " %s %s" % ("-Glp", prop.username)

    su_sudo = utils.su_sudo()
    password_f = None
    if su_sudo is "su":
        name, version, is_su = utils.os_release()
        log.debug("name = %s version = %s is_su = %s" % (name, version, is_su))
        if (name == 'Fedora' and version >= '14' and is_su == True):
            #using su opening GUI apps fail in Fedora 14.
            #To run GUI apps as root, you need a root login shell (su -) in Fedora 14
            su_sudo = 'su - -c "%s"'
        else:
            su_sudo = 'su -c "%s"'

        password_f = "get_password_ui"
#        password_f = utils.get_password
    cmd = su_sudo % usermod
    log.info("cmd = %s" % cmd)
    #    sts, output = utils.run(cmd, True, password_f, -1,True,cmd)
    sts, output = utils.run(
        cmd, True, password_f, 1, True,
        "Please enter root/superuser password to add 'lp' group")
    if sts == 0:
        result = True

    return result
예제 #5
0
파일: queues.py 프로젝트: Distrotech/hplip
def add_group(core):
    result = False
    add_user_to_group = core.get_distro_ver_data('add_user_to_group', '')
    if add_user_to_group:
        usermod = os.path.join(utils.which("usermod"), "usermod") + " %s %s" % (add_user_to_group, prop.username)
    else:
        usermod = os.path.join(utils.which("usermod"), "usermod") + " %s %s" % ("-Glp", prop.username)

    su_sudo = utils.su_sudo()
    password_f = None
    if su_sudo is "su":
        name,version,is_su = utils.os_release()
        log.debug("name = %s version = %s is_su = %s" %(name,version,is_su))
        if ( name == 'Fedora' and version >= '14' and is_su == True):
           #using su opening GUI apps fail in Fedora 14. 
           #To run GUI apps as root, you need a root login shell (su -) in Fedora 14   
           su_sudo = 'su - -c "%s"'
        else:
           su_sudo = 'su -c "%s"'

        password_f = "get_password_ui"
#        password_f = utils.get_password
    cmd =su_sudo % usermod
    log.info("cmd = %s" %cmd)
#    sts, output = utils.run(cmd, True, password_f, -1,True,cmd)  
    sts, output = utils.run(cmd, True, password_f, 1, True, "Please enter root/superuser password to add 'lp' group")
    if sts == 0:
        result = True
        
    return result
예제 #6
0
    def handle_hplip_updation(self):
        log.debug("handle_hplip_updation upgrade_notify =%d"%(self.user_settings.upgrade_notify))
        path = utils.which('hp-upgrade')
        if self.user_settings.upgrade_notify is False:
            log.debug("upgrade notification is disabled in systray ")
            if path:
                path = os.path.join(path, 'hp-upgrade')
                log.debug("Running hp-upgrade: %s " % (path))
                # this just updates the available version in conf file. But won't notify
                os.spawnlp(os.P_NOWAIT, path, 'hp-upgrade', '--check')
                time.sleep(5)
                try:
                    os.waitpid(0, os.WNOHANG)
                except OSError:
                    pass
            return


        current_time = time.time()

        if int(current_time) > self.user_settings.upgrade_pending_update_time:
            path = utils.which('hp-upgrade')
            if path:
                path = os.path.join(path, 'hp-upgrade')
                log.debug("Running hp-upgrade: %s " % (path))
                os.spawnlp(os.P_NOWAIT, path, 'hp-upgrade', '--notify')
                time.sleep(5)
            else:
                log.error("Unable to find hp-upgrade --notify on PATH.")
        else:
            log.debug("upgrade schedule time is not yet completed. schedule time =%d current time =%d " %(self.user_settings.upgrade_pending_update_time, current_time))
        try:
            os.waitpid(0, os.WNOHANG)
        except OSError:
            pass
예제 #7
0
def install_plugin(core):
    plugin_sts = core.get_plugin_status()
    if plugin_sts == PLUGIN_VERSION_MISMATCH:
        ok,user_input =tui.enter_choice("Found Plugin version mismatch. Press 'y' to re-install the plugin(y=yes*, n=no):",['y', 'n'], 'y')
    elif plugin_sts == PLUGIN_FILES_CORRUPTED:
        ok,user_input =tui.enter_choice("Plugins corrupted. Press 'y' to re-install the plugin(y=yes*, n=no):",['y', 'n'], 'y')
    elif plugin_sts == PLUGIN_NOT_INSTALLED:
        ok,user_input =tui.enter_choice("Plugin's are missing. Press 'y' to install the plugin(y=yes*, n=no):",['y', 'n'], 'y')
    elif plugin_sts == PLUGIN_INSTALLED:
        log.info("Plugin's already installed")
        return True
    else:
        log.info("No plug-in printers are configured.")
        return True

    if ok and user_input == 'y':
#        authenticate(core)
        cmd=utils.which('hp-plugin',True)
        if cmd:
            cmd = core.passwordObj.getAuthCmd() %append_options(cmd)
            sts = os_utils.execute(cmd)
            if sts == 0:
                return True
        else:
            log.error("Failed to locate hp-plugin command")
    else:
        log.info(log.bold("Please run 'hp-plugin' command in root mode to install the Plugin's"))
    return False
예제 #8
0
def merge_PDF_viewer(output,ocr):
    pdf_viewer = ''
    pdf_viewer_list = ['kpdf', 'acroread', 'xpdf', 'evince', 'xdg-open']
    for v in pdf_viewer_list:
        vv = utils.which(v)
        if vv:
            pdf_viewer = os.path.join(vv, v)
            break
            #cmd = "%s %s &" % (pdf_viewer, output_pdf)
    if ocr == True:
        g = output.split(".pdf")
        output_ocr = g[0] +"_ocr.pdf"
        if sys.version_info[0] == 3:
            cmd = "ocrmypdf" + " " + output + " " + output_ocr
        else:
            cmd = "pypdfocr" + "  " + output
        os_utils.execute(cmd)
        #g = output.split(".")
        #output_ocr = g[0] +"_ocr.pdf"
        if os.path.isfile(output_ocr):
            #print("File Exists")
            cmd = pdf_viewer + "  " + output_ocr + " " + "&"
        else:
            cmd = pdf_viewer + "  " + output + " " + "&"
        os_utils.execute(cmd)
    else:
        cmd = pdf_viewer + "  " + output + " " + "&"
        #print(cmd)               
        os_utils.execute(cmd)
예제 #9
0
    def toolbox_triggered(self):
        try:
            os.waitpid(-1, os.WNOHANG)
        except OSError:
            pass

        # See if it is already running...
        ok, lock_file = utils.lock_app('hp-toolbox', True)

        if ok: # able to lock, not running...
            utils.unlock(lock_file)

            path = utils.which('hp-toolbox')
            if path:
                path = os.path.join(path, 'hp-toolbox')
            else:
                log.error("Unable to find hp-toolbox on PATH.")

                self.tray_icon.showMessage("HPLIP Status Service",
                                self.__tr("Unable to locate hp-toolbox on system PATH."),
                                self.icon_error, 5000)

                return

            log.debug(path)
            os.spawnlp(os.P_NOWAIT, path, 'hp-toolbox')

        else: # ...already running, raise it
            device.Event('', '', EVENT_RAISE_DEVICE_MANAGER).send_via_dbus(SessionBus(), 'com.hplip.Toolbox')
예제 #10
0
파일: doctor.py 프로젝트: rfabbri/hplip
def install_plugin(core):
    plugin_sts = core.get_plugin_status()
    if plugin_sts == PLUGIN_VERSION_MISMATCH:
        ok,user_input =tui.enter_choice("Found Plugin version mismatch. Press 'y' to re-install the plugin(y=yes*, n=no):",['y', 'n'], 'y')
    elif plugin_sts == PLUGIN_FILES_CORRUPTED:
        ok,user_input =tui.enter_choice("Plugins corrupted. Press 'y' to re-install the plugin(y=yes*, n=no):",['y', 'n'], 'y')
    elif plugin_sts == PLUGIN_NOT_INSTALLED:
        ok,user_input =tui.enter_choice("Plugin's are missing. Press 'y' to install the plugin(y=yes*, n=no):",['y', 'n'], 'y')
    elif plugin_sts == PLUGIN_INSTALLED:
        log.info("Plugin's already installed")
        return True
    else:
        log.info("No plug-in printers are configured.")
        return True

    if ok and user_input == 'y':
#        authenticate(core)
        cmd=utils.which('hp-plugin',True)
        if cmd:
            cmd = core.passwordObj.getAuthCmd() %append_options(cmd)
            sts = os_utils.execute(cmd)
            if sts == 0:
                return True
        else:
            log.error("Failed to locate hp-plugin command")
    else:
        log.info(log.bold("Please run 'hp-plugin' command in root mode to install the Plugin's"))
    return False
예제 #11
0
    def NextButton_clicked (self):
        if self.dontRemindRadioBtton.isChecked():
            log.debug("HPLIP Upgrade, selected Don't remind again radiobutton")
            user_conf.set('upgrade', 'notify_upgrade', 'false')
            msg= "Check for HPLIP updates is disabled. To enable it again, change 'Settings' in 'HP systemtray' "
            SuccessUI(self, self.__tr(msg))

        elif self.remindRadioBtton.isChecked():
            schedule_days = str(self.daysSpinBox.value())
            log.debug("HPLIP Upgrade, selected remind later radiobutton  days= %d" %(int(schedule_days)))
            next_time = time.time() + (int(schedule_days) *24 * 60 *60) 
            user_conf.set('upgrade', 'pending_upgrade_time', str(int(next_time)))
        else:
            log.debug("HPLIP Upgrade, selected Install radiobutton  distro_type=%d" %self.distro_tier)
            self.NextButton.setEnabled(False)
            if self.distro_tier != 1:		# not tier 1 distro
                log.debug("OK pressed for tier 2 distro pressed")
                utils.openURL(MANUAL_INSTALL_LINK)
                
                ## TBD::open browser
            else:
                terminal_cmd = utils.get_terminal()
                if terminal_cmd is not None and utils.which("hp-upgrade"):
                    cmd = terminal_cmd + " 'hp-upgrade'"
                    log.debug("cmd = %s " %cmd)
                    os.system(cmd)
                    self.result = True
                else:
                    log.error("Failed to run hp-upgrade command from terminal =%s "%terminal_cmd)
                    ErrorUI(self, self.__tr("Failed to run hp-upgrade"))

        self.close()
예제 #12
0
파일: dcheck.py 프로젝트: rfabbri/hplip
def update_ld_output():
    # For library checks
    global ld_output
    status, ld_output = utils.run('%s -p' % os.path.join(utils.which('ldconfig'), 'ldconfig'), log_output=False)

    if status != 0:
        log.debug("ldconfig failed.")
예제 #13
0
    def NextButton_clicked (self):
        if self.dontRemindRadioBtton.isChecked():
            log.debug("HPLIP Upgrade, selected Don't remind again radiobutton")
            user_conf.set('upgrade', 'notify_upgrade', 'false')
            msg= "Check for HPLIP updates is disabled. To Upgrade again, check it in 'HP-toolbox' "
            self.SuccessUI( self.__tr(msg))
        elif self.remindRadioBtton.isChecked():
            schedule_days = str(self.daysSpinBox.value())
            log.debug("HPLIP Upgrade, selected remind later radiobutton  days= %d" %(int(schedule_days)))
            next_time = time.time() + (int(schedule_days) *24 * 60 *60)
            user_conf.set('upgrade', 'pending_upgrade_time', str(int(next_time)))
        else:
            log.debug("HPLIP Upgrade, selected Install radiobutton  distro_type=%d" %self.distro_type)
            self.NextButton.setEnabled(False)
            if self.distro_type != 1:     # not tier 1 distro
                utils.openURL(MANUAL_INSTALL_LINK)
            else:
                terminal_cmd = utils.get_terminal()
                if terminal_cmd is not None and utils.which("hp-upgrade"):
                    cmd = terminal_cmd + " 'hp-upgrade -w'"
                    os_utils.execute(cmd)
                    self.result = True
                else:
                    log.error("Failed to run hp-upgrade command from terminal =%s "%terminal_cmd)
                    self.FailureUI( self.__tr("Failed to run hp-upgrade"))

        self.close()
예제 #14
0
def backup_clearLog(strLog):
    if os.path.exists(strLog):
        iArch = 1
        while os.path.exists("%s.%d" % (strLog, iArch)) or os.path.exists(
                "%s.%d.gz" % (strLog, iArch)):
            iArch += 1
        sts, out = utils.run('cp %s %s.%d' % (strLog, strLog, iArch))
        if sts != 0:
            log.error("Failed to archive %s log file" % strLog)
        else:
            cmd = 'cat /dev/null > %s' % strLog
            sts = os_utils.execute(cmd)
            if sts != 0:
                log.warn("Failed to clear the %s log file" % strLog)
            if utils.which('gzip'):
                sts, out = utils.run('gzip %s.%d' % (strLog, iArch))
                if sts != 0:
                    log.info("Existing %s log file copied to %s.%d" %
                             (strLog, strLog, iArch))
                else:
                    log.info("Existing %s log file copied to %s.%d.gz" %
                             (strLog, strLog, iArch))
            else:
                log.info("Existing %s log file copied to %s.%d" %
                         (strLog, strLog, iArch))
예제 #15
0
    def toolboxTriggered(self):
        try:
            os.waitpid(-1, os.WNOHANG)
        except OSError:
            pass

        # See if it is already running...
        ok, lock_file = utils.lock_app('hp-toolbox', True)

        if ok: # able to lock, not running...
            utils.unlock(lock_file)

            path = utils.which('hp-toolbox')
            if path:
                path = os.path.join(path, 'hp-toolbox')
            else:
                self.tray_icon.showMessage(self.__tr("HPLIP Status Service"),
                                self.__tr("Unable to locate hp-toolbox on system PATH."),
                                QSystemTrayIcon.Critical, TRAY_MESSAGE_DELAY)

                log.error("Unable to find hp-toolbox on PATH.")
                return

            #log.debug(path)
            log.debug("Running hp-toolbox: hp-toolbox")
            os.spawnlp(os.P_NOWAIT, path, 'hp-toolbox')

        else: # ...already running, raise it
            self.sendMessage('', '', EVENT_RAISE_DEVICE_MANAGER, interface='com.hplip.Toolbox')
예제 #16
0
def update_ld_output():
    # For library checks
    global ld_output
    status, ld_output = utils.run('%s -p' % os.path.join(utils.which('ldconfig'), 'ldconfig'), log_output=False)

    if status != 0:
        log.debug("ldconfig failed.")
예제 #17
0
    def NextButton_clicked (self):
        if self.dontRemindRadioBtton.isChecked():
            log.debug("HPLIP Upgrade, selected Don't remind again radiobutton")
            user_conf.set('upgrade', 'notify_upgrade', 'false')
            msg= "Check for HPLIP updates is disabled. To enable it again, change 'Settings' in 'HP systemtray' "
            SuccessUI(self, self.__tr(msg))

        elif self.remindRadioBtton.isChecked():
            schedule_days = str(self.daysSpinBox.value())
            log.debug("HPLIP Upgrade, selected remind later radiobutton  days= %d" %(int(schedule_days)))
            next_time = time.time() + (int(schedule_days) *24 * 60 *60) 
            user_conf.set('upgrade', 'pending_upgrade_time', str(int(next_time)))
        else:
            log.debug("HPLIP Upgrade, selected Install radiobutton  distro_type=%d" %self.distro_tier)
            self.NextButton.setEnabled(False)
            if self.distro_tier != 1:		# not tier 1 distro
                log.debug("OK pressed for tier 2 distro pressed")
                utils.openURL(MANUAL_INSTALL_LINK)
                
                ## TBD::open browser
            else:
                terminal_cmd = utils.get_terminal()
                if terminal_cmd is not None and utils.which("hp-upgrade"):
                    cmd = terminal_cmd + " 'hp-upgrade -w'"
                    log.debug("cmd = %s " %cmd)
                    os.system(cmd)
                    self.result = True
                else:
                    log.error("Failed to run hp-upgrade command from terminal =%s "%terminal_cmd)
                    ErrorUI(self, self.__tr("Failed to run hp-upgrade"))

        self.close()
예제 #18
0
def handle_fax_event(event, pipe_name):
    if event.event_code == EVENT_FAX_RENDER_COMPLETE and \
        event.username == prop.username:

        fax_file_fd, fax_file_name = tempfile.mkstemp(prefix="hpfax-")
        pipe = os.open(pipe_name, os.O_RDONLY)
        bytes_read = 0
        while True:
            data = os.read(pipe, PIPE_BUF)
            if not data:
                break

            os.write(fax_file_fd, data)
            bytes_read += len(data)

        log.debug("Saved %d bytes to file %s" % (bytes_read, fax_file_name))

        os.close(pipe)
        os.close(fax_file_fd)

        devices[event.device_uri].faxes[(event.username, event.job_id)] = \
            device.FaxEvent(fax_file_name, event)

        show_waiting_faxes(event.device_uri)

        try:
            os.waitpid(-1, os.WNOHANG)
        except OSError:
            pass

        # See if hp-sendfax is already running for this queue
        ok, lock_file = utils.lock_app('hp-sendfax-%s' % event.printer_name,
                                       True)

        if ok:
            # able to lock, not running...
            utils.unlock(lock_file)

            path = utils.which('hp-sendfax')
            if path:
                path = os.path.join(path, 'hp-sendfax')
            else:
                log.error("Unable to find hp-sendfax on PATH.")
                return

            log.debug("Running hp-sendfax: %s --printer=%s" %
                      (path, event.printer_name))
            os.spawnlp(os.P_NOWAIT, path, 'hp-sendfax',
                       '--printer=%s' % event.printer_name)

        else:
            # cannot lock file - hp-sendfax is running
            # no need to do anything... hp-sendfax is polling
            log.debug(
                "hp-sendfax is running. Waiting for CheckForWaitingFax() call."
            )

    else:
        log.warn("Not handled!")
        pass
예제 #19
0
    def __validatePlugin(self,plugin_file, digsig_file, req_checksum):
        calc_checksum = get_checksum(file(plugin_file, 'r').read())
        log.debug("D/L file checksum=%s" % calc_checksum)

        if req_checksum and req_checksum != calc_checksum:
            return PLUGIN_INSTALL_ERROR_PLUGIN_FILE_CHECKSUM_ERROR

        gpg = utils.which('gpg',True)
        if gpg:
            cmd = '%s --no-permission-warning --keyserver pgp.mit.edu --recv-keys 0xA59047B9' % gpg
            log.info("Receiving digital keys: %s" % cmd)
            status, output = utils.run(cmd)
            log.debug(output)

            if status != 0:
                return PLUGIN_INSTALL_ERROR_UNABLE_TO_RECV_KEYS

            cmd = '%s --no-permission-warning --verify %s %s' % (gpg, digsig_file, plugin_file)
            log.debug("Verifying plugin with digital keys: %s" % cmd)
            status, output = utils.run(cmd)
            log.debug(output)
            log.debug("%s status: %d" % (gpg, status))

            if status != 0:
                return PLUGIN_INSTALL_ERROR_DIGITAL_SIGN_BAD

        return PLUGIN_INSTALL_ERROR_NONE
예제 #20
0
def merge_PDF_viewer(output,ocr):
    pdf_viewer = ''
    pdf_viewer_list = ['kpdf', 'acroread', 'xpdf', 'evince', 'xdg-open']
    for v in pdf_viewer_list:
        vv = utils.which(v)
        if vv:
            pdf_viewer = os.path.join(vv, v)
            break
            #cmd = "%s %s &" % (pdf_viewer, output_pdf)
    if ocr == True:
        g = output.split(".pdf")
        output_ocr = g[0] +"_ocr.pdf"
        if sys.version_info[0] == 3:
            cmd = "ocrmypdf" + " " + output + " " + output_ocr
        else:
            cmd = "pypdfocr" + "  " + output
        os_utils.execute(cmd)
        #g = output.split(".")
        #output_ocr = g[0] +"_ocr.pdf"
        if os.path.isfile(output_ocr):
            #print("File Exists")
            cmd = pdf_viewer + "  " + output_ocr + " " + "&"
        else:
            cmd = pdf_viewer + "  " + output + " " + "&"
        os_utils.execute(cmd)
    else:
        cmd = pdf_viewer + "  " + output + " " + "&"
        #print(cmd)               
        os_utils.execute(cmd)
예제 #21
0
    def toolboxTriggered(self):
        try:
            os.waitpid(-1, os.WNOHANG)
        except OSError:
            pass

        # See if it is already running...
        ok, lock_file = utils.lock_app('hp-toolbox', True)

        if ok: # able to lock, not running...
            utils.unlock(lock_file)

            path = utils.which('hp-toolbox')
            if path:
                path = os.path.join(path, 'hp-toolbox')
            else:
                self.tray_icon.showMessage(self.__tr("HPLIP Status Service"),
                                self.__tr("Unable to locate hp-toolbox on system PATH."),
                                QSystemTrayIcon.Critical, TRAY_MESSAGE_DELAY)

                log.error("Unable to find hp-toolbox on PATH.")
                return

            #log.debug(path)
            log.debug("Running hp-toolbox: hp-toolbox")
            os.spawnlp(os.P_NOWAIT, path, 'hp-toolbox')

        else: # ...already running, raise it
            self.sendMessage('', '', EVENT_RAISE_DEVICE_MANAGER, interface='com.hplip.Toolbox')
예제 #22
0
def get_usb_details(vid_pid):
    result_cnt = 0
    param_result = {"idVendor":'', "iProduct":'',  "bNumInterfaces":'', "bInterfaceClass":''}
    param_search = {"idVendor": re.compile(r"""\s*idVendor\s*([0-9a-fx]{1,})\s*.*""", re.I),
                    "iProduct" : re.compile(r"""\s*iProduct\s*[0-9a-fx]{1,}\s*(.*)""", re.I),
                    "bNumInterfaces" : re.compile(r"""\s*bNumInterfaces\s*(\d{1,})\s*.*""", re.I),
                    "bInterfaceClass" : re.compile(r"""\s*bInterfaceClass\s*(\d{1,})\s*.*""", re.I)  }

    lsusb_cmd = utils.which('lsusb',True)
    if lsusb_cmd:
        sts,out = utils.run("%s -d %s -v"%(lsusb_cmd, vid_pid), passwordObj = None, pswd_msg='', log_output=False)
        if sts == 0:
            for l in out.splitlines():
                for s in param_search:
                    if s in l:
                        result_cnt += 1
                        if param_search[s].match(l):
                            param_result[s] = param_search[s].match(l).group(1)
                        else:
                            log.warn("TBD... Shouldn't have entered into this condition. key[%s]"%s)

                        if "idVendor" ==  s and param_result[s].lower() != "0x03f0":  # if non-HP vendor, ignoring usb parsing.
                            return False, {}
                        elif "iProduct" == s and param_result[s] == "":
                            return False, {}

                        break

                if result_cnt == len(param_result):  # To avoid extra parsing...
                     break

    return True, param_result
예제 #23
0
def enablePrinter(printer_name):
    setPasswordPrompt(
        "You do not have permission to enable a printer. You need authentication."
    )
    cmd_full_path = utils.which('cupsenable', True)
    cmd = "%s %s" % (cmd_full_path, printer_name)
    return os_utils.execute(cmd)
예제 #24
0
    def NextButton_clicked(self):
        beginWaitCursor()
        try:
            if self.Error_msg == QUEUES_SMART_INSTALL_ENABLED:
                self.disable_smart_install()

            elif self.Error_msg == QUEUES_PAUSED:
                cups.enablePrinter(self.printerName)
                msg = "'" + self.printerName + "' is enabled successfully"
                SuccessUI(self, self.__tr(msg))

            else:
                status, status_str = cups.cups_operation(
                    cups.delPrinter, GUI_MODE, 'qt4', self, self.printerName)

                if status != cups.IPP_OK:
                    msg = "Failed to remove ' " + self.printerName + " ' queue.\nRemove using hp-toolbox..."
                    FailureUI(self, self.__tr(msg))
                else:
                    msg = "' " + self.printerName + " ' removed successfully.\nRe-configuring this printer by hp-setup..."
                    log.debug(msg)
                    path = utils.which('hp-setup')
                    if path:
                        log.debug("Starting hp-setup")
                        utils.run('hp-setup --gui')

        finally:
            endWaitCursor()
        self.result = True
        self.close()
예제 #25
0
파일: systemtray.py 프로젝트: super11/hplip
    def toolbox_triggered(self):
        try:
            os.waitpid(-1, os.WNOHANG)
        except OSError:
            pass

        # See if it is already running...
        ok, lock_file = utils.lock_app('hp-toolbox', True)

        if ok:  # able to lock, not running...
            utils.unlock(lock_file)

            path = utils.which('hp-toolbox')
            if path:
                path = os.path.join(path, 'hp-toolbox')
            else:
                log.error("Unable to find hp-toolbox on PATH.")

                self.tray_icon.showMessage(
                    "HPLIP Status Service",
                    self.__tr("Unable to locate hp-toolbox on system PATH."),
                    self.icon_error, 5000)

                return

            log.debug(path)
            os.spawnlp(os.P_NOWAIT, path, 'hp-toolbox')

        else:  # ...already running, raise it
            device.Event('', '', EVENT_RAISE_DEVICE_MANAGER).send_via_dbus(
                SessionBus(), 'com.hplip.Toolbox')
예제 #26
0
    def NextButton_clicked(self):
        beginWaitCursor()
        try:
            if self.Error_msg ==  QUEUES_SMART_INSTALL_ENABLED:
                self.disable_smart_install()

            elif  self.Error_msg == QUEUES_PAUSED:
                cups.enablePrinter(self.printerName)
                msg ="'"+self.printerName+"' is enabled successfully"
                SuccessUI(self, self.__tr(msg))

            else:
                status, status_str = cups.cups_operation(cups.delPrinter, GUI_MODE, 'qt4', self, self.printerName)

                if status != cups.IPP_OK:
                    msg="Failed to remove ' "+self.printerName+" ' queue.\nRemove using hp-toolbox..."
                    FailureUI(self, self.__tr(msg))
                else:
                    msg="' "+self.printerName+" ' removed successfully.\nRe-configuring this printer by hp-setup..."
                    log.debug(msg)
                    path = utils.which('hp-setup')
                    if path:
                        log.debug("Starting hp-setup")
                        utils.run('hp-setup --gui')

        finally:
            endWaitCursor()
        self.result = True
        self.close()
예제 #27
0
    def __getPluginInformation(self, callback=None):
        status, url, check_sum = ERROR_NO_NETWORK, '', ''

        if self.__plugin_conf_file.startswith('http://'):
            if not utils.check_network_connection():
                log.error("Network connection not detected.")
                return ERROR_NO_NETWORK, '', 0

        local_conf_fp, local_conf = utils.make_temp_file()

        try:
            try:
                if self.__plugin_conf_file.startswith('file://'):
                    status, filename = utils.download_from_network(
                        self.__plugin_conf_file, local_conf, True)
                else:
                    wget = utils.which("wget", True)
                    if wget:
                        status, output = utils.run(
                            "%s --tries=3 --timeout=60 --output-document=%s %s --cache=off"
                            % (wget, local_conf, self.__plugin_conf_file))
                        if status:
                            log.error(
                                "Plugin download failed with error code = %d" %
                                status)
                            return status, url, check_sum
                    else:
                        log.error(
                            "Please install wget package to download the plugin."
                        )
                        return status, url, check_sum
            except IOError as e:
                log.error("I/O Error: %s" % e.strerror)
                return status, url, check_sum

            if not os.path.exists(local_conf):
                log.error("plugin.conf not found.")
                return status, url, check_sum

            try:
                plugin_conf_p = ConfigBase(local_conf)
                url = plugin_conf_p.get(self.__required_version, 'url', '')
                check_sum = plugin_conf_p.get(self.__required_version,
                                              'checksum')
                status = ERROR_SUCCESS
            except (KeyError, configparser.NoSectionError) as e:
                log.error(
                    "Error reading plugin.conf: Missing section [%s]  Error[%s]"
                    % (self.__required_version, e))
                return ERROR_FILE_NOT_FOUND, url, check_sum

            if url == '':
                return ERROR_FILE_NOT_FOUND, url, check_sum

        finally:
            os.close(local_conf_fp)
            os.remove(local_conf)

        return status, url, check_sum
예제 #28
0
    def __setup(self,  cmds):
        for c in cmds:
            basename = c.split()[0]
            path = utils.which(basename)
            if path:
                return ' '.join([os.path.join(path, basename), ' '.join(c.split()[1:])])

        return ''
예제 #29
0
    def __setup(self,  cmds):
        for c in cmds:
            basename = c.split()[0]
            path = utils.which(basename)
            if path:
                return ' '.join([os.path.join(path, basename), ' '.join(c.split()[1:])])

        return ''
예제 #30
0
def check_lsmod(module):
    global mod_output

    if not mod_output:
        lsmod = utils.which('lsmod')
        status, mod_output = utils.run(os.path.join(lsmod, 'lsmod'), log_output=False)

    return mod_output.find(module) >= 0
예제 #31
0
파일: dcheck.py 프로젝트: rfabbri/hplip
def check_lsmod(module):
    global mod_output

    if not mod_output:
        lsmod = utils.which('lsmod')
        status, mod_output = utils.run(os.path.join(lsmod, 'lsmod'), log_output=False)

    return mod_output.find(module) >= 0
예제 #32
0
파일: queues.py 프로젝트: Distrotech/hplip
def reconfigure_Queue(que, mode, dialog= None,app=None):
    global Error_Found
    Error_msg =None
    if mode == INTERACTIVE_MODE:
        if 'hp' in que.DeviceType or 'hpfax' in que.DeviceType:
            if que.PPDFileError ==  False:
                log.debug("'%s' is configured correctly." %(que.PrinterName))
            else:
                Error_msg = "PPD file for '%s' is not correct. Need to choose correct PPD file." %(que.PrinterName)
        else:
            Error_msg ="'%s' is not configured using HPLIP. Need to remove and re-cofigure using hp-setup." %(que.PrinterName)


        if Error_msg != None:
            Error_Found = True
            log.error(Error_msg)
            response, value = tui.enter_yes_no("Do you want to remove and re-configure?")
            if response == False:
                log.debug("User Exit")
                sys.exit(1)
            elif value == True:
                cups.delPrinter(que.PrinterName)
                log.info("' %s' removed successfully.\nRe-configuring this printer by hp-setup..."%que.PrinterName)
                path = utils.which('hp-setup')
                if path:
                    log.debug("Starting hp-setup")
                    os.system('hp-setup -i')
        elif que.IsEnabled == False:
            Error_Found = True
            responce, value =tui.enter_yes_no("'%s Queue is paused. Do you want to enable queue?"%(que.PrinterName))
            if responce == False:
                log.debug("User Exit")
                sys.exit(1)
            elif value == True:
                cups.enablePrinter(que.PrinterName)
                log.info("'%s' is enabled successfully"%que.PrinterName)
            else:
                log.info("Manually enable '%s'."%que.PrinterName)
    else:
        if 'hp' in que.DeviceType or 'hpfax' in que.DeviceType:
            if que.PPDFileError ==  False:
                log.debug("'%s' is configured correctly." %(que.PrinterName))
            else:
                log.error("PPD file for '%s' is not correct. Need to choose correct PPD file." %(que.PrinterName))
                Error_msg = QUEUES_INCORRECT_PPD
        else:
            log.error("'%s' is not configured using HPLIP. Need to remove and re-cofigure using hp-setup." %(que.PrinterName))
            Error_msg =QUEUES_CONFIG_ERROR

        if Error_msg == None and que.IsEnabled == False:
            Error_msg = QUEUES_PAUSED

        if Error_msg and dialog and app:
            Error_Found = True
            dialog.init(que.PrinterName, que.DeviceURI, Error_msg)
            dialog.show()
            log.debug("Starting GUI loop...")
            app.exec_()
예제 #33
0
def handle_fax_event(event, pipe_name):
    if event.event_code == EVENT_FAX_RENDER_COMPLETE and \
        event.username == prop.username:

        fax_file_fd, fax_file_name = tempfile.mkstemp(prefix="hpfax-")
        pipe = os.open(pipe_name, os.O_RDONLY)
        bytes_read = 0
        while True:
            data = os.read(pipe, PIPE_BUF)
            if not data:
                break

            os.write(fax_file_fd, data)
            bytes_read += len(data)

        log.debug("Saved %d bytes to file %s" % (bytes_read, fax_file_name))

        os.close(pipe)
        os.close(fax_file_fd)

        devices[event.device_uri].faxes[(event.username, event.job_id)] = \
            device.FaxEvent(fax_file_name, event)

        show_waiting_faxes(event.device_uri)

        try:
            os.waitpid(-1, os.WNOHANG)
        except OSError:
            pass

        # See if hp-sendfax is already running for this queue
        ok, lock_file = utils.lock_app('hp-sendfax-%s' % event.printer_name, True)

        if ok:
            # able to lock, not running...
            utils.unlock(lock_file)

            path = utils.which('hp-sendfax')
            if path:
                path = os.path.join(path, 'hp-sendfax')
            else:
                log.error("Unable to find hp-sendfax on PATH.")
                return

            log.debug("Running hp-sendfax: %s --printer=%s" % (path, event.printer_name))
            os.spawnlp(os.P_NOWAIT, path, 'hp-sendfax',
                '--printer=%s' % event.printer_name)

        else:
            # cannot lock file - hp-sendfax is running
            # no need to do anything... hp-sendfax is polling
            log.debug("hp-sendfax is running. Waiting for CheckForWaitingFax() call.")

    else:
        log.warn("Not handled!")
        pass
예제 #34
0
def restart(passwordObj):
    ok = False
    shutdown = utils.which('shutdown')
    if shutdown and passwordObj:
        cmd = "%s -r now" % (os.path.join(shutdown, "shutdown"))
        cmd = passwordObj.getAuthCmd() % cmd
        status, output = utils.run(cmd, passwordObj, "Need authentication to restart system")

        ok = (status == 0)
    return ok
예제 #35
0
def handle_printer_diagnose():
    path = utils.which('hp-diagnose_queues')
    if path:
        path = os.path.join(path, 'hp-diagnose_queues')
    else:
        log.error("Unable to find hp-diagnose_queues on PATH.")
        return

    log.debug("Running hp-diagnose_queues: %s" % (path))
    os.spawnlp(os.P_NOWAIT, path, 'hp-diagnose_queues', '-s')
예제 #36
0
파일: hpssd.py 프로젝트: csteacherd22/hplip
def handle_printer_diagnose():
    path = utils.which('hp-diagnose_queues')
    if path:
        path = os.path.join(path, 'hp-diagnose_queues')
    else:
        log.error("Unable to find hp-diagnose_queues on PATH.")
        return

    log.debug("Running hp-diagnose_queues: %s" % (path))
    os.spawnlp(os.P_NOWAIT, path, 'hp-diagnose_queues','-s')
예제 #37
0
def enable_log():
    result = False
    cmd = 'cp -f %s %s' % (CUPS_FILE, CUPS_BACKUP_FILE)
    log.debug("Backup CUPS conf file. cmd =%s" % cmd)
    sts, out = utils.run(cmd)
    if sts != 0:
        log.error("Failed to take back cups file=%s" % CUPS_FILE)

    #check if cups is log level enabled or disable
    cmd = "grep 'LogLevel warn' %s" % CUPS_FILE
    log.debug("cmd= %s" % cmd)
    sts, out = utils.run(cmd)
    if sts == 0:
        cmd = "vi -c '%s/LogLevel warn/LogLevel debug\rhpLogLevel 15/' -c 'wq' %s" % (
            "%s", CUPS_FILE)
        log.debug("Changing 'Log level' to debug. cmd=%s" % cmd)
        sts, cmd = utils.run(cmd)
        if sts != 0:
            log.error("Failed to update Loglevel to Debug in cups=%s" %
                      CUPS_FILE)

        cmd = None
        if utils.which('service'):
            cmd = os.path.join(utils.which('service'),
                               'service') + " cups restart"
        elif utils.which('systemctl'):
            cmd = os.path.join(
                utils.which('systemctl'),
                'systemctl') + " restart %s.service" % service_name
        elif os.path.exists('/etc/init.d/cups'):
            cmd = "/etc/init.d/cups restart"
        else:
            log.error(
                "service command not found.. Please restart cups manually..")

        if cmd:
            log.debug("CUPS restart cmd = %s" % cmd)
            sts, out = utils.run(cmd)
            if sts == 0:
                result = True

    return result
예제 #38
0
def restart(passwordObj):
    ok = False
    shutdown = utils.which('shutdown')
    if shutdown and passwordObj:
        cmd = "%s -r now" % (os.path.join(shutdown, "shutdown"))
        cmd = passwordObj.getAuthCmd() % cmd
        status, output = utils.run(cmd, passwordObj,
                                   "Need authentication to restart system")

        ok = (status == 0)
    return ok
예제 #39
0
def run_hp_tools(cmd):
    if cmd is not None:
        hpCommand = utils.which(cmd, True)

        if not hpCommand:
            hpCommand = cmd

        log.debug(hpCommand)
        status, output = utils.run(hpCommand)
        return status == 0
    else:
        log.error("Command not found")
        return False
예제 #40
0
def run_hp_tools(cmd):
    if cmd is not None:
        hpCommand = utils.which(cmd, True)

        if not hpCommand:
            hpCommand = cmd

        log.debug(hpCommand)
        status, output = utils.run(hpCommand)
        return status == 0
    else:
        log.error("Command not found")
        return False
예제 #41
0
def run_systray():
    path = utils.which('hp-systray')
    if path:
        path = os.path.join(path, 'hp-systray')
    else:
        path = os.path.join(prop.home_dir, 'systray.py')

    if not os.path.exists(path):
        log.warn("Unable to start hp-systray")

    log.debug("Running hp-systray: %s --force-startup" % path)
    os.spawnlp(os.P_NOWAIT, path, 'hp-systray', '--force-startup', "--ignore-update-firsttime")
    log.debug("Waiting for hp-systray to start...")
    time.sleep(1)
예제 #42
0
def start_systray():
    tui.title("RE-STARTING HP_SYSTRAY")
    path = utils.which('hp-systray')
    if path:
        path = os.path.join(path, 'hp-systray')
    else:
        path = os.path.join(prop.home_dir, 'systray.py')
    if not os.path.exists(path):
        log.warn("Unable to start hp-systray")

    log.debug("Running hp-systray: %s --force-startup" % path)
    os.spawnlp(os.P_NOWAIT, path, 'hp-systray', '--force-startup')
    log.debug("Waiting for hp-systray to start...")
    time.sleep(1)
예제 #43
0
def get_usb_details(vid_pid):
    result_cnt = 0
    param_result = {
        "idVendor": '',
        "iProduct": '',
        "bNumInterfaces": '',
        "bInterfaceClass": ''
    }
    param_search = {
        "idVendor":
        re.compile(r"""\s*idVendor\s*([0-9a-fx]{1,})\s*.*""", re.I),
        "iProduct":
        re.compile(r"""\s*iProduct\s*[0-9a-fx]{1,}\s*(.*)""", re.I),
        "bNumInterfaces":
        re.compile(r"""\s*bNumInterfaces\s*(\d{1,})\s*.*""", re.I),
        "bInterfaceClass":
        re.compile(r"""\s*bInterfaceClass\s*(\d{1,})\s*.*""", re.I)
    }

    lsusb_cmd = utils.which('lsusb', True)
    if lsusb_cmd:
        sts, out = utils.run("%s -d %s -v" % (lsusb_cmd, vid_pid),
                             passwordObj=None,
                             pswd_msg='',
                             log_output=False)
        if sts == 0:
            for l in out.splitlines():
                for s in param_search:
                    if s in l:
                        result_cnt += 1
                        if param_search[s].match(l):
                            param_result[s] = param_search[s].match(l).group(1)
                        else:
                            log.warn(
                                "TBD... Shouldn't have entered into this condition. key[%s]"
                                % s)

                        if "idVendor" == s and param_result[s].lower(
                        ) != "0x03f0":  # if non-HP vendor, ignoring usb parsing.
                            return False, {}
                        elif "iProduct" == s and param_result[s] == "":
                            return False, {}

                        break

                if result_cnt == len(
                        param_result):  # To avoid extra parsing...
                    break

    return True, param_result
예제 #44
0
    def __getPluginInformation(self, callback=None):
        status, url, check_sum = ERROR_NO_NETWORK, '',''

        if self.__plugin_conf_file.startswith('http://'):
            if not utils.check_network_connection():
                log.error("Network connection not detected.")
                return ERROR_NO_NETWORK, '', 0

        local_conf_fp, local_conf = utils.make_temp_file()

        try:
            try:
                if self.__plugin_conf_file.startswith('file://'):
                    status, filename = utils.download_from_network(self.__plugin_conf_file, local_conf, True)
                else:
                    wget = utils.which("wget", True)
                    if wget:
                        status, output = utils.run("%s --timeout=60 --output-document=%s %s --cache=off" %(wget, local_conf, self.__plugin_conf_file))
                        if status:
                            log.error("Plugin download failed with error code = %d" %status)
                            return status, url, check_sum
                    else:
                        log.error("Please install wget package to download the plugin.")
                        return status, url, check_sum
            except IOError as e:
                log.error("I/O Error: %s" % e.strerror)
                return status, url, check_sum

            if not os.path.exists(local_conf):
                log.error("plugin.conf not found.")
                return status, url, check_sum

            try:
                plugin_conf_p = ConfigBase(local_conf)
                url = plugin_conf_p.get(self.__required_version, 'url','')
                check_sum  = plugin_conf_p.get(self.__required_version, 'checksum')
                status = ERROR_SUCCESS
            except (KeyError, configparser.NoSectionError) as e:
                log.error("Error reading plugin.conf: Missing section [%s]  Error[%s]" % (self.__required_version,e))
                return ERROR_FILE_NOT_FOUND, url, check_sum

            if url == '':
                return ERROR_FILE_NOT_FOUND, url, check_sum

        finally:
            os.close(local_conf_fp)
            os.remove(local_conf)

        return status, url, check_sum
예제 #45
0
파일: validation.py 프로젝트: shekhei/hplip
    def __init__(self, pgp_site = 'pgp.mit.edu', key = 0xA59047B9):
        self.__pgp_site = pgp_site
        self.__key = key
        self.__gpg = utils.which('gpg',True)

        sts, self.__hplipdir = os_utils.getHPLIPDir()
        self.__gpg_dir = os.path.join(self.__hplipdir, ".gnupg")
        
        if not os.path.exists(self.__gpg_dir):
            try:
                os.mkdir(self.__gpg_dir, 0755)
            except OSError:
                log.error("Failed to create %s" % self.__gpg_dir)

        self.__change_owner()
예제 #46
0
def enable_log():
    result = False
    cmd='cp -f %s %s'%(CUPS_FILE,CUPS_BACKUP_FILE)
    log.debug("Backup CUPS conf file. cmd =%s"%cmd)
    sts,out=utils.run(cmd)
    if sts != 0:
        log.error("Failed to take back cups file=%s"%CUPS_FILE)

    #check if cups is log level enabled or disable
    cmd="grep 'LogLevel warn' %s"%CUPS_FILE
    log.debug ("cmd= %s"%cmd)
    sts,out=utils.run(cmd)
    if sts == 0:
        cmd = "sed -i 's/LogLevel.*warn/LogLevel debug\rhpLogLevel 15/' %s "%CUPS_FILE
        log.debug("Changing 'Log level' to debug. cmd=%s"%cmd)
        sts= os.system(cmd)
        if sts != 0:
           log.error("Failed to update Loglevel to Debug in cups=%s"%CUPS_FILE)

        cmd=None
        if utils.which('service'):
           cmd = os.path.join(utils.which('service'), 'service')+" cups restart"
        elif utils.which('systemctl'):
           cmd = os.path.join(utils.which('systemctl'), 'systemctl')+" restart %s.service"%service_name
        elif os.path.exists('/etc/init.d/cups'):
           cmd = "/etc/init.d/cups restart"
        else:
           log.error("service command not found.. Please restart cups manually..")

        if cmd:
           log.debug("CUPS restart cmd = %s"%cmd)
           sts,out = utils.run(cmd)
           if sts == 0:
               result = True

    return result
예제 #47
0
def run_hp_tools_with_auth(cmd, passwordObj):
    if cmd is not None and passwordObj  is not None :
        hpCommand = utils.which(cmd,True)

        if not hpCommand:   #if it is local command like. ./setup.py
            hpCommand = cmd

        hpCommand = passwordObj.getAuthCmd() % hpCommand

        log.debug(hpCommand)
        status, output = utils.run(hpCommand, passwordObj, "Need authentication to run %s command"%cmd)
        return status == 0
    else:
        log.error("Command not found or password object is not valid")
        return False
예제 #48
0
def run_systray():
    path = utils.which('hp-systray')
    if path:
        path = os.path.join(path, 'hp-systray')
    else:
        path = os.path.join(prop.home_dir, 'systray.py')

    if not os.path.exists(path):
        log.warn("Unable to start hp-systray")

    log.debug("Running hp-systray: %s --force-startup" % path)
    os.spawnlp(os.P_NOWAIT, path, 'hp-systray', '--force-startup',
               "--ignore-update-firsttime")
    log.debug("Waiting for hp-systray to start...")
    time.sleep(1)
예제 #49
0
    def __init__(self, pgp_site='pgp.mit.edu', key=0xA59047B9):
        self.__pgp_site = pgp_site
        self.__key = key
        self.__gpg = utils.which('gpg', True)

        sts, self.__hplipdir = os_utils.getHPLIPDir()
        self.__gpg_dir = os.path.join(self.__hplipdir, ".gnupg")

        if not os.path.exists(self.__gpg_dir):
            try:
                os.mkdir(self.__gpg_dir, 0755)
            except OSError:
                log.error("Failed to create %s" % self.__gpg_dir)

        self.__change_owner()
예제 #50
0
    def __init__(self,
                 device_uri=None,
                 printer_name=None,
                 callback=None,
                 fax_type=FAX_TYPE_NONE,
                 disable_dbus=False):

        FaxDevice.__init__(self, device_uri, printer_name, callback, fax_type,
                           disable_dbus)

        self.send_fax_thread = None
        self.upload_log_thread = None

        try:
            sendfax_path = utils.which('hp-sendfax')
            sendfax_a_path = os.readlink(sendfax_path + "/hp-sendfax")
            if not os.path.isabs(sendfax_a_path):
                sendfax_f_path = os.path.join(sendfax_path, sendfax_a_path)
            else:
                sendfax_f_path = sendfax_a_path

            sendfax_abs_path = os.path.realpath(sendfax_f_path)
            (head, tail) = os.path.split(sendfax_abs_path)

            lib_name = head + "/fax/plugins/fax_marvell.so"
            log.debug("Load the library %s\n" % lib_name)
            from installer import pluginhandler
            pluginObj = pluginhandler.PluginHandle()

            if pluginObj.getStatus() != pluginhandler.PLUGIN_INSTALLED:
                log.error(
                    "Loading %s failed. Try after installing plugin libraries\n"
                    % lib_name)
                log.info(
                    "Run \"hp-plugin\" to installa plugin libraries if you are not automatically prompted\n"
                )
                job_id = 0
                self.service.SendEvent(device_uri, printer_name,
                                       EVENT_FAX_FAILED_MISSING_PLUGIN,
                                       os.getenv('USER'), job_id,
                                       "Plugin is not installed")
                sys.exit(1)
            else:
                self.libfax_marvell = cdll.LoadLibrary(lib_name)
        except Error as e:
            log.error("Loading fax_marvell failed (%s)\n" % e.msg)
            sys.exit(1)
예제 #51
0
def run_hp_tools_with_auth(cmd, passwordObj):
    if cmd is not None and passwordObj is not None:
        hpCommand = utils.which(cmd, True)

        if not hpCommand:  #if it is local command like. ./setup.py
            hpCommand = cmd

        hpCommand = passwordObj.getAuthCmd() % hpCommand

        log.debug(hpCommand)
        status, output = utils.run(
            hpCommand, passwordObj,
            "Need authentication to run %s command" % cmd)
        return status == 0
    else:
        log.error("Command not found or password object is not valid")
        return False
예제 #52
0
    def __init__(self, pgp_site = 'pgp.mit.edu', key = 0x4ABA2F66DBD5A95894910E0673D770CDA59047B9):
        self.__pgp_site = pgp_site
        self.__key = key
        self.__gpg = utils.which('gpg',True)

        sts, self.__hplipdir = os_utils.getHPLIPDir()
        self.__gpg_dir = os.path.join(self.__hplipdir, ".gnupg")

        #Make sure gpg directory is present. GPG keys will be retrieved here from the key server
        

        if not os.path.exists(self.__gpg_dir):
            try:
                os.mkdir(self.__gpg_dir, 0o755)
            except OSError:
                log.error("Failed to create %s" % self.__gpg_dir)
        self.__change_owner()
예제 #53
0
def get_smartinstall_enabled_devices():
    smartinstall_dev_list = []
    lsusb_cmd = utils.which("lsusb", True)

    if not lsusb_cmd:
        log.error("Failed to find the lsusb command")
        return smartinstall_dev_list

    try:
        sts, out = utils.run(lsusb_cmd)
        if sts != 0:
            log.error("Failed to run the %s command" % lsusb_cmd)
            return smartinstall_dev_list

        for d in out.splitlines():
            usb_dev_pat = re.compile(r""".*([0-9a-f]{4}:([0-9a-f]{4}))\s*""", re.I)

            if usb_dev_pat.match(d):
                vid_pid = usb_dev_pat.match(d).group(1)

                bsts, usb_params = get_usb_details(vid_pid)
                if not bsts:
                    continue  # These are not HP-devices

                log.debug(
                    "Product['%s'],Interfaces[%s],InterfaceClass[%s]"
                    % (usb_params["iProduct"], usb_params["bNumInterfaces"], usb_params["bInterfaceClass"])
                )
                if (
                    usb_params["bNumInterfaces"] == "1"
                    and usb_params["bInterfaceClass"] == "8"
                    and "laserjet" in usb_params["iProduct"].lower()
                ):  #'8' is MASS STORAGE
                    smartinstall_dev_list.append(usb_params["iProduct"])

            else:
                log.warn("Failed to find vid and pid for USB device[%s]" % d)

    except KeyError:
        pass

    if smartinstall_dev_list:
        smartinstall_dev_list = utils.uniqueList(smartinstall_dev_list)

    return smartinstall_dev_list
예제 #54
0
    def __init__(self,
                 pgp_site='pgp.mit.edu',
                 key=0x4ABA2F66DBD5A95894910E0673D770CDA59047B9):
        self.__pgp_site = pgp_site
        self.__key = key
        self.__gpg = utils.which('gpg', True)

        sts, self.__hplipdir = os_utils.getHPLIPDir()
        self.__gpg_dir = os.path.join(self.__hplipdir, ".gnupg")

        #Make sure gpg directory is present. GPG keys will be retrieved here from the key server

        if not os.path.exists(self.__gpg_dir):
            try:
                os.mkdir(self.__gpg_dir, 0o755)
            except OSError:
                log.error("Failed to create %s" % self.__gpg_dir)
        self.__change_owner()
예제 #55
0
파일: password.py 프로젝트: rfabbri/hplip
def get_distro_name():
    os_name = None;
    if utils.which('lsb_release'):
       name = os.popen('lsb_release -i | cut -f 2')
       os_name = name.read().strip()
       name.close()

    if not os_name:
       name = os.popen("cat /etc/issue | awk '{print $1}' | head -n 1")
       os_name = name.read().strip()
       name.close()

    if "redhatenterprise" in os_name.lower():
        os_name = 'rhel'
    elif "suse" in os_name.lower():
        os_name = 'suse'

    return os_name
예제 #56
0
파일: password.py 프로젝트: super11/hplip
def get_distro_name():
    os_name = None
    if utils.which('lsb_release'):
        name = os.popen('lsb_release -i | cut -f 2')
        os_name = name.read().strip()
        name.close()

    if not os_name:
        name = os.popen("cat /etc/issue | awk '{print $1}' | head -n 1")
        os_name = name.read().strip()
        name.close()

    if "redhatenterprise" in os_name.lower():
        os_name = 'rhel'
    elif "suse" in os_name.lower():
        os_name = 'suse'

    return os_name
예제 #57
0
파일: avahi.py 프로젝트: rfabbri/hplip
def detectNetworkDevices(ttl=4, timeout=10):
    found_devices = {}

    if utils.which("avahi-browse") == '':
        log.error("Avahi-browse is not installed")
        return found_devices

    addr4 = []
    addr6 = []
    # Obtain all the resolved services which has service type '_printer._tcp' from avahi-browse
    p = Popen(['avahi-browse', '-kprt', '_printer._tcp'], stdout=PIPE)
    for line in p.stdout:
        if line.startswith('='):
            bits = line.split(';')
            if is_ipv6(bits[7]) and bits[2] == 'IPv6':
                addr6.append([bits[7], bits[8]])
                # We don't support IPv6 yet
                continue
            elif bits[2] == 'IPv4':
                addr4.append([bits[7], bits[8]])
            ip = bits[7]
            port = bits[8]
            # Run through the offered addresses and see if we have a bound local
            # address for it.
            try:
                res = socket.getaddrinfo(ip, port, 0, 0, 0, socket.AI_ADDRCONFIG)
                if res:
                    y = {'num_devices' : 1, 'num_ports': 1, 'product_id' : '', 'mac': '',
                         'status_code': 0, 'device2': '0', 'device3': '0', 'note': ''}
                    y['ip'] = ip
                    y['hn'] = bits[6].replace('.local', '')
                    details = bits[9].split('" "')
                    for item in details:
                        key, value = item.split('=')
                        if key == 'ty':
                            y['mdns'] = value
                            y['device1'] = "MFG:Hewlett-Packard;MDL:%s;CLS:PRINTER;" % value
                    found_devices[y['ip']] = y
                    log.debug("ip=%s hn=%s ty=%s" %(ip,y['hn'], y['mdns']))
            except socket.gaierror:
                pass
    log.debug("Found %d devices" % len(found_devices))

    return found_devices
예제 #58
0
def get_smartinstall_enabled_devices():
    smartinstall_dev_list = []
    lsusb_cmd = utils.which('lsusb', True)

    if not lsusb_cmd:
        log.error("Failed to find the lsusb command")
        return smartinstall_dev_list

    try:
        sts, out = utils.run(lsusb_cmd)
        if sts != 0:
            log.error("Failed to run the %s command" % lsusb_cmd)
            return smartinstall_dev_list

        for d in out.splitlines():
            usb_dev_pat = re.compile(r""".*([0-9a-f]{4}:([0-9a-f]{4}))\s*""",
                                     re.I)

            if usb_dev_pat.match(d):
                vid_pid = usb_dev_pat.match(d).group(1)

                bsts, usb_params = get_usb_details(vid_pid)
                if not bsts:
                    continue  # These are not HP-devices

                log.debug(
                    "Product['%s'],Interfaces[%s],InterfaceClass[%s]" %
                    (usb_params["iProduct"], usb_params["bNumInterfaces"],
                     usb_params["bInterfaceClass"]))
                if usb_params["bNumInterfaces"] == '1' and usb_params[
                        "bInterfaceClass"] == '8' and "laserjet" in usb_params[
                            "iProduct"].lower():  #'8' is MASS STORAGE
                    smartinstall_dev_list.append(usb_params["iProduct"])

            else:
                log.warn("Failed to find vid and pid for USB device[%s]" % d)

    except KeyError:
        pass

    if smartinstall_dev_list:
        smartinstall_dev_list = utils.uniqueList(smartinstall_dev_list)

    return smartinstall_dev_list
예제 #59
0
파일: avahi.py 프로젝트: super11/hplip
def detectNetworkDevices(ttl=4, timeout=10):
    found_devices = {}

    if utils.which("avahi-browse") == '':
        log.error("Avahi-browse is not installed")
        return found_devices

    addr4 = []
    addr6 = []
    # Obtain all the resolved services which has service type '_printer._tcp' from avahi-browse
    p = Popen(['avahi-browse', '-kprt', '_printer._tcp'], stdout=PIPE)
    for line in p.stdout:
        if line.startswith('='):
            bits = line.split(';')
            if is_ipv6(bits[7]) and bits[2] == 'IPv6':
                addr6.append([bits[7], bits[8]])
                # We don't support IPv6 yet
                continue
            elif bits[2] == 'IPv4':
                addr4.append([bits[7], bits[8]])
            ip = bits[7]
            port = bits[8]
            # Run through the offered addresses and see if we have a bound local
            # address for it.
            try:
                res = socket.getaddrinfo(ip, port, 0, 0, 0, socket.AI_ADDRCONFIG)
                if res:
                    y = {'num_devices' : 1, 'num_ports': 1, 'product_id' : '', 'mac': '',
                         'status_code': 0, 'device2': '0', 'device3': '0', 'note': ''}
                    y['ip'] = ip
                    y['hn'] = bits[6].replace('.local', '')
                    details = bits[9].split('" "')
                    for item in details:
                        key, value = item.split('=', 1)
                        if key == 'ty':
                            y['mdns'] = value
                            y['device1'] = "MFG:Hewlett-Packard;MDL:%s;CLS:PRINTER;" % value
                    found_devices[y['ip']] = y
                    log.debug("ip=%s hn=%s ty=%s" %(ip,y['hn'], y['mdns']))
            except socket.gaierror:
                pass
    log.debug("Found %d devices" % len(found_devices))

    return found_devices