コード例 #1
0
def main(args=None, five_to_six_script=False):
    parser = OptionParser(usage=USAGE, formatter=WrappedIndentedHelpFormatter())
    add_parser_options(parser, five_to_six_script)

    # In testing we sometimes specify args, otherwise use the default:
    if not args:
        args = sys.argv[1:]

    (options, args) = parser.parse_args(args)
    set_defaults(options, five_to_six_script)
    validate_options(options)
    MigrationEngine(options).main()
コード例 #2
0
def main():
    parser = OptionParser(usage=USAGE,
                          formatter=WrappedIndentedHelpFormatter())
    parser.add_option("--register", action='store_true',
                      help=_("launches the registration dialog on startup"))
    options, args = parser.parse_args(args=sys.argv)

    log = logging.getLogger("rhsm-app.subscription-manager-gui")

    try:
        bus = dbus.SessionBus()
    except dbus.exceptions.DBusException as e:
        log.debug("Enabled to connect to dbus SessionBus")
        log.exception(e)
        # Just ignore it if for some reason we can't find the session bus
        bus = None

    if already_running(bus):
        # Attempt to raise the running instance to the forefront
        try:
            remote_object = bus.get_object(BUS_NAME, BUS_PATH)
            remote_object.show_window(dbus_interface=BUS_NAME)
            log.debug("subscription-manager-gui already running, showing main window")
        except dbus.exceptions.DBusException as e:
            log.debug("Error attempting to show main window via dbus")
            log.debug("dbus remote_object with no show_window: %s" % remote_object)
            log.debug(e)
            # failed to raise the window, maybe we raced dbus?
            # fallback to opening a new window
        else:
            # we raised the existing window, we are done
            sys.exit()

    try:
        main = managergui.MainWindow(auto_launch_registration=options.register)

        # Hook into dbus service - only if it is available
        if bus:
            SubscriptionManagerService(main.main_window)

        # Exit the gtk loop when the window is closed
        main.main_window.connect('hide', ga_Gtk.main_quit)

        sys.exit(ga_Gtk.main() or 0)
    except SystemExit as e:
        # this is a non-exceptional exception thrown by Python 2.4, just
        # re-raise, bypassing handle_exception
        raise e
    except KeyboardInterrupt:
        system_exit(0, "\nUser interrupted process.")
    except Exception as e:
        log.exception(e)
        system_exit(1, e)
コード例 #3
0
def main(args=None, five_to_six_script=False):
    parser = OptionParser(usage=USAGE, formatter=WrappedIndentedHelpFormatter())
    add_parser_options(parser, five_to_six_script)

    # In testing we sometimes specify args, otherwise use the default:
    if not args:
        args = sys.argv[1:]

    (options, args) = parser.parse_args(args)
    set_defaults(options, five_to_six_script)
    validate_options(options)
    MigrationEngine(options).main()
コード例 #4
0
    def test_cat_manifest(self):
        catman = CatManifestCommand()
        parser = OptionParser()
        parser.add_option("--no-content")
        (options, args) = parser.parse_args([])
        catman.options = options
        catman.args = [_build_valid_manifest()]

        with Capture() as cap:
            catman._do_command()

        self.assertEqual("", cap.err)
        self.assert_string_equals(manifestdata.correct_manifest_output, cap.out)
コード例 #5
0
ファイル: migrate.py プロジェクト: rholy/subscription-manager
    def __init__(self):
        self.rhncfg = initUp2dateConfig()
        self.rhsmcfg = rhsm.config.initConfig()

        self.proxy_host = None
        self.proxy_port = None
        self.proxy_user = None
        self.proxy_pass = None

        self.cp = None
        self.db = ProductDatabase()

        self.parser = OptionParser(usage=USAGE,
                                   formatter=WrappedIndentedHelpFormatter())
        self.add_parser_options()
コード例 #6
0
def main():
    logutil.init_logger()
    log = logging.getLogger('rhsm-app.' + __name__)

    parser = OptionParser(usage=USAGE,
                          formatter=WrappedIndentedHelpFormatter())
    parser.add_option("--autoheal", dest="autoheal", action="store_true",
            default=False, help="perform an autoheal check")
    parser.add_option("--force", dest="force", action="store_true",
            default=False, help=SUPPRESS_HELP)
    (options, args) = parser.parse_args()
    try:
        _main(options, log)
    except SystemExit as se:
        # sys.exit triggers an exception in older Python versions, which
        # in this case  we can safely ignore as we do not want to log the
        # stack trace. We need to check the code, since we want to signal
        # exit with failure to the caller. Otherwise, we will exit with 0
        if se.code:
            sys.exit(-1)
    except Exception as e:
        log.error("Error while updating certificates using daemon")
        print(_('Unable to update entitlement certificates and repositories'))
        log.exception(e)
        sys.exit(-1)
コード例 #7
0
    def __init__(self, name="cli", aliases=None, shortdesc=None, primary=False):
        self.name = name
        self.shortdesc = shortdesc
        self.primary = primary
        self.aliases = aliases or []

        # include our own HelpFormatter that doesn't try to break
        # long words, since that fails on multibyte words
        self.parser = OptionParser(usage=self._get_usage(), description=shortdesc,
                                   formatter=WrappedIndentedHelpFormatter())
コード例 #8
0
def main():
    logutil.init_logger()
    log = logging.getLogger('rhsm-app.' + __name__)

    parser = OptionParser(usage=USAGE,
                          formatter=WrappedIndentedHelpFormatter())
    parser.add_option("--autoheal", dest="autoheal", action="store_true",
            default=False, help="perform an autoheal check")
    (options, args) = parser.parse_args()
    try:
        _main(options, log)
    except SystemExit as se:
        # sys.exit triggers an exception in older Python versions, which
        # in this case  we can safely ignore as we do not want to log the
        # stack trace. We need to check the code, since we want to signal
        # exit with failure to the caller. Otherwise, we will exit with 0
        if se.code:
            sys.exit(-1)
    except Exception as e:
        log.error("Error while updating certificates using daemon")
        print(_('Unable to update entitlement certificates and repositories'))
        log.exception(e)
        sys.exit(-1)
コード例 #9
0
def main(args=None, five_to_six_script=False):
    parser = OptionParser(usage=USAGE, formatter=WrappedIndentedHelpFormatter())
    add_parser_options(parser, five_to_six_script)

    # In testing we sometimes specify args, otherwise use the default:
    if not args:
        args = sys.argv[1:]

    (options, args) = parser.parse_args(args)
    set_defaults(options, five_to_six_script)
    validate_options(options)
    MigrationEngine(options).main()

    # Try to enable yum plugins: subscription-manager and product-id
    enabled_yum_plugins = repolib.YumPluginManager.enable_yum_plugins()
    if len(enabled_yum_plugins) > 0:
        print(_('WARNING') + '\n\n' + repolib.YumPluginManager.warning_message(enabled_yum_plugins) + '\n')

    try:
        sys.stdout.flush()
        sys.stderr.flush()
    except IOError as io_err:
        log.error("Error: Unable to print data to stdout/stderr output during exit process: %s" % io_err)
コード例 #10
0
    def __init__(self):
        self.rhncfg = initUp2dateConfig()
        self.rhsmcfg = rhsm.config.initConfig()

        self.proxy_host = None
        self.proxy_port = None
        self.proxy_user = None
        self.proxy_pass = None

        self.cp = None
        self.db = ProductDatabase()

        self.parser = OptionParser(usage=USAGE, formatter=WrappedIndentedHelpFormatter())
        self.add_parser_options()
コード例 #11
0
def main(args=None, five_to_six_script=False):
    parser = OptionParser(usage=USAGE, formatter=WrappedIndentedHelpFormatter())
    add_parser_options(parser, five_to_six_script)

    # In testing we sometimes specify args, otherwise use the default:
    if not args:
        args = sys.argv[1:]

    (options, args) = parser.parse_args(args)
    set_defaults(options, five_to_six_script)
    validate_options(options)
    MigrationEngine(options).main()

    # Try to enable yum plugins: subscription-manager and product-id
    enabled_yum_plugins = repolib.YumPluginManager.enable_pkg_plugins()
    if len(enabled_yum_plugins) > 0:
        print(_('WARNING') + '\n\n' + repolib.YumPluginManager.warning_message(enabled_yum_plugins) + '\n')

    try:
        sys.stdout.flush()
        sys.stderr.flush()
    except IOError as io_err:
        log.error("Error: Unable to print data to stdout/stderr output during exit process: %s" % io_err)
コード例 #12
0
class CLICommand(object):
    """
    Base class for rt commands. This class provides a templated run
    strategy.
    """
    def __init__(self, name="cli", short_desc=None):
        self.shortdesc = short_desc
        self.name = name
        self.parser = OptionParser(usage=self._get_usage(),
                                   description=self.shortdesc)
        self._define_custom_opts(self.parser)

    def run(self, args=None):
        # Initialize args
        if args is None:
            # Skip the program name and the command name.
            args = sys.argv[2:]

        (self.options, self.args) = self.parser.parse_args(args)

        self._validate_options()
        self._run_command()

    def _get_usage(self):
        return _("%%prog %s [OPTIONS]") % self.name

    def _define_custom_opts(self, parser):
        """
        Defines any custom opt args for this command.
        """
        pass

    def _validate_options(self):
        '''
        Validates the command's arguments.
        @raise InvalidCLIOptionError: Raised when arg validation fails.
        '''
        # No argument validation by default.
        pass

    def _run_command(self):
        """
        Does the work that this command intends.
        """
        raise NotImplementedError(
            "Commands must implement: _run_command(self)")
コード例 #13
0
ファイル: cli.py プロジェクト: beav/subscription-manager
class CLICommand(object):
    """
    Base class for rt commands. This class provides a templated run
    strategy.
    """
    def __init__(self, name="cli", short_desc=None):
        self.shortdesc = short_desc
        self.name = name
        self.parser = OptionParser(usage=self._get_usage(), description=self.shortdesc)
        self._define_custom_opts(self.parser)

    def run(self, args=None):
        # Initialize args
        if args is None:
            # Skip the program name and the command name.
            args = sys.argv[2:]

        (self.options, self.args) = self.parser.parse_args(args)

        self._validate_options()
        self._run_command()

    def _get_usage(self):
        return _("%%prog %s [OPTIONS]") % self.name

    def _define_custom_opts(self, parser):
        """
        Defines any custom opt args for this command.
        """
        pass

    def _validate_options(self):
        '''
        Validates the command's arguments.
        @raise InvalidCLIOptionError: Raised when arg validation fails.
        '''
        # No argument validation by default.
        pass

    def _run_command(self):
        """
        Does the work that this command intends.
        """
        raise NotImplementedError("Commands must implement: _run_command(self)")
コード例 #14
0
    except connection.GoneException, ge:
        uuid = ConsumerIdentity.read().getConsumerId()
        if ge.deleted_id == uuid:
            log.critical(_("This consumer's profile has been deleted from the server. Its local certificates will now be archived"))
            managerlib.clean_all_data()
            log.critical(_("Certificates archived to '/etc/pki/consumer.old'. Contact your system administrator if you need more information."))

        raise ge


if __name__ == '__main__':

    logutil.init_logger()
    log = logging.getLogger('rhsm-app.' + __name__)

    parser = OptionParser(usage=USAGE,
                          formatter=WrappedIndentedHelpFormatter())
    parser.add_option("--autoheal", dest="autoheal", action="store_true",
            default=False, help="perform an autoheal check")
    (options, args) = parser.parse_args()
    try:
        main(options, log)
    except SystemExit, se:
        # sys.exit triggers an exception in older Python versions, which
        # in this case  we can safely ignore as we do not want to log the
        # stack trace. We need to check the code, since we want to signal
        # exit with failure to the caller. Otherwise, we will exit with 0
        if se.code:
            sys.exit(-1)
    except Exception, e:
        log.error("Error while updating certificates using daemon")
        print _('Unable to update entitlement certificates and repositories')
コード例 #15
0
ファイル: migrate.py プロジェクト: rholy/subscription-manager
class MigrationEngine(object):
    def __init__(self):
        self.rhncfg = initUp2dateConfig()
        self.rhsmcfg = rhsm.config.initConfig()

        self.proxy_host = None
        self.proxy_port = None
        self.proxy_user = None
        self.proxy_pass = None

        self.cp = None
        self.db = ProductDatabase()

        self.parser = OptionParser(usage=USAGE,
                                   formatter=WrappedIndentedHelpFormatter())
        self.add_parser_options()

    def add_parser_options(self):
        self.parser.add_option("-f",
                               "--force",
                               action="store_true",
                               default=False,
                               help=_("ignore channels not available on RHSM"))
        self.parser.add_option(
            "-g",
            "--gui",
            action="store_true",
            default=False,
            dest='gui',
            help=
            _("launch the GUI tool to attach subscriptions, instead of auto-attaching"
              ))
        self.parser.add_option(
            "-n",
            "--no-auto",
            action="store_true",
            default=False,
            dest='noauto',
            help=
            _("don't execute the auto-attach option while registering with subscription manager"
              ))
        self.parser.add_option(
            "-s",
            "--servicelevel",
            dest="servicelevel",
            help=_(
                "service level to follow when attaching subscriptions, for no service "
                "level use --servicelevel=\"\""))
        self.parser.add_option(
            "--serverurl",
            dest='serverurl',
            help=_("specify the subscription management server to migrate to"))
        self.parser.add_option("--redhat-user",
                               dest="redhatuser",
                               help=_("specify the Red Hat user name"))
        self.parser.add_option("--redhat-password",
                               dest="redhatpassword",
                               help=_("specify the Red Hat password"))
        self.parser.add_option(
            "--subscription-service-user",
            dest="subserviceuser",
            help=_("specify the subscription service user name"))
        self.parser.add_option(
            "--subscription-service-password",
            dest="subservicepassword",
            help=_("specify the subscription service password"))
        # See BZ 915847 - some users want to connect to RHN with a proxy but to RHSM without a proxy
        self.parser.add_option(
            "--no-proxy",
            action="store_true",
            dest='noproxy',
            help=
            _("don't use RHN proxy settings with subscription management server"
              ))
        self.parser.add_option("--org",
                               dest='org',
                               help=_("organization to register to"))
        self.parser.add_option("--environment",
                               dest='environment',
                               help=_("environment to register to"))

    def validate_options(self):
        if self.options.servicelevel and self.options.noauto:
            system_exit(
                1,
                _("The --servicelevel and --no-auto options cannot be used together."
                  ))

    def authenticate(self, username, password, user_prompt, pw_prompt):
        if not username:
            username = raw_input(user_prompt).strip()

        if not password:
            password = getpass.getpass(prompt=pw_prompt)

        return UserCredentials(username, password)

    def is_hosted(self):
        hostname = self.rhsmcfg.get('server', 'hostname')
        if re.search('subscription\.rhn\.(.*\.)*redhat\.com', hostname):
            return True  # re.search doesn't return a boolean
        else:
            return False

    def get_auth(self):
        self.rhncreds = self.authenticate(self.options.redhatuser,
                                          self.options.redhatpassword,
                                          _("Red Hat username: "******"Red Hat password: "******"Subscription Service username: "******"Subscription Service password: "******"http://":
                http_proxy = http_proxy[7:]
            try:
                self.proxy_host, self.proxy_port = http_proxy.split(':')
            except ValueError, e:
                log.exception(e)
                system_exit(1, _("Unable to read RHN proxy settings."))

            if self.rhncfg['enableProxyAuth']:
                self.proxy_user = self.rhncfg['proxyUser']
                self.proxy_pass = self.rhncfg['proxyPassword']

            log.info("Using proxy %s:%s" % (self.proxy_host, self.proxy_port))
            if self.options.noproxy:
                # If the user doesn't want to use a proxy to connect to their subscription
                # management server, then remove any proxy information that may have crept in.
                self.rhsmcfg.set('server', 'proxy_hostname', '')
                self.rhsmcfg.set('server', 'proxy_port', '')
                self.rhsmcfg.set('server', 'proxy_user', '')
                self.rhsmcfg.set('server', 'proxy_password', '')
            else:
                self.rhsmcfg.set('server', 'proxy_hostname', self.proxy_host)
                self.rhsmcfg.set('server', 'proxy_port', self.proxy_port)
                self.rhsmcfg.set('server', 'proxy_user', self.proxy_user or '')
                self.rhsmcfg.set('server', 'proxy_password', self.proxy_pass
                                 or '')
            self.rhsmcfg.save()
コード例 #16
0
 def __init__(self, name="cli", short_desc=None):
     self.shortdesc = short_desc
     self.name = name
     self.parser = OptionParser(usage=self._get_usage(),
                                description=self.shortdesc)
     self._define_custom_opts(self.parser)
コード例 #17
0
def main():

    log.info("rhsmd started")
    parser = OptionParser(usage=USAGE,
                          formatter=WrappedIndentedHelpFormatter())
    parser.add_option("-d",
                      "--debug",
                      dest="debug",
                      help="Display debug messages",
                      action="store_true",
                      default=False)
    parser.add_option(
        "-k",
        "--keep-alive",
        dest="keep_alive",
        help="Stay running (don't shut down after the first dbus call)",
        action="store_true",
        default=False)
    parser.add_option("-s",
                      "--syslog",
                      dest="syslog",
                      help="Run standalone and log result to syslog",
                      action="store_true",
                      default=False)
    parser.add_option(
        "-f",
        "--force-signal",
        dest="force_signal",
        help="Force firing of a signal " +
        "(valid, expired, warning, partial, classic or registration_required)")
    parser.add_option(
        "-i",
        "--immediate",
        dest="immediate",
        action="store_true",
        default=False,
        help="Fire forced signal immediately (requires --force-signal)")

    options, args = parser.parse_args()

    force_signal = parse_force_signal(options.force_signal)

    if options.immediate and force_signal is None:
        print_error("--immediate must be used with --force-signal")
        sys.exit(-2)

    global enable_debug
    enable_debug = options.debug

    # short-circuit dbus initialization
    if options.syslog:
        log.info("logging subscription status to syslog")
        status = check_status(force_signal)
        if status == RHSM_EXPIRED:
            log_syslog(
                syslog.LOG_NOTICE,
                "This system is missing one or more subscriptions. " +
                "Please run subscription-manager for more information.")
        elif status == RHSM_PARTIALLY_VALID:
            log_syslog(
                syslog.LOG_NOTICE,
                "This system is missing one or more subscriptions " +
                "to fully cover its products. " +
                "Please run subscription-manager for more information.")
        elif status == RHSM_WARNING:
            log_syslog(
                syslog.LOG_NOTICE,
                "This system's subscriptions are about to expire. " +
                "Please run subscription-manager for more information.")
        elif status == RHN_CLASSIC:
            log_syslog(syslog.LOG_INFO,
                       get_branding().RHSMD_REGISTERED_TO_OTHER)
        elif status == RHSM_REGISTRATION_REQUIRED:
            log_syslog(
                syslog.LOG_NOTICE,
                "In order for Subscription Manager to provide your " +
                "system with updates, your system must be registered " +
                "with the Customer Portal. Please enter your Red Hat " +
                "login to ensure your system is up-to-date.")

        # Return an exit code for the program. having valid entitlements is
        # good, so it gets an exit status of 0.
        return status

    # we are not running from cron here, so unset the excepthook
    # though, we may be running from cli, or as a dbus activation. For
    # cli, we should traceback. For dbus, we should try to log it and
    # raise dbus exception?
    sys.excepthook = sys.__excepthook__

    system_bus = dbus.SystemBus()
    loop = ga_GObject.MainLoop()
    checker = StatusChecker(system_bus, options.keep_alive, force_signal, loop)

    if options.immediate:
        checker.entitlement_status_changed(force_signal)

    loop.run()
コード例 #18
0
    except connection.GoneException, ge:
        uuid = ConsumerIdentity.read().getConsumerId()
        if ge.deleted_id == uuid:
            log.critical(_("This consumer's profile has been deleted from the server. It's local certificates will now be archived"))
            managerlib.clean_all_data()
            log.critical(_("Certificates archived to '/etc/pki/consumer.old'. Contact your system administrator if you need more information."))
        else:
            raise ge


if __name__ == '__main__':

    logutil.init_logger()
    log = logging.getLogger('rhsm-app.' + __name__)

    parser = OptionParser()
    parser.add_option("--autoheal", dest="autoheal", action="store_true",
            default=False, help="perform an autoheal check")
    (options, args) = parser.parse_args()
    try:
        main(options, log)
    except SystemExit:
        # sys.exit triggers an exception in older Python versions, which
        # in this case  we can safely ignore as we do not want to log the
        # stack trace.
        pass
    except Exception, e:
        log.error("Error while updating certificates using daemon")
        print _('Unable to update entitlement certificates and repositories')
        log.exception(e)
        sys.exit(-1)
コード例 #19
0
def main():

    log.info("rhsmd started")
    parser = OptionParser(usage=USAGE,
                          formatter=WrappedIndentedHelpFormatter())
    parser.add_option("-d", "--debug", dest="debug",
            help="Display debug messages", action="store_true", default=False)
    parser.add_option("-k", "--keep-alive", dest="keep_alive",
            help="Stay running (don't shut down after the first dbus call)",
            action="store_true", default=False)
    parser.add_option("-s", "--syslog", dest="syslog",
            help="Run standalone and log result to syslog",
            action="store_true", default=False)
    parser.add_option("-f", "--force-signal", dest="force_signal",
            help="Force firing of a signal " +
            "(valid, expired, warning, partial, classic or registration_required)")
    parser.add_option("-i", "--immediate", dest="immediate",
            action="store_true", default=False,
            help="Fire forced signal immediately (requires --force-signal)")

    options, args = parser.parse_args()

    force_signal = parse_force_signal(options.force_signal)

    if options.immediate and force_signal is None:
        print_error("--immediate must be used with --force-signal")
        sys.exit(-2)

    global enable_debug
    enable_debug = options.debug

    # short-circuit dbus initialization
    if options.syslog:
        log.info("logging subscription status to syslog")
        status = check_status(force_signal)
        if status == RHSM_EXPIRED:
            log_syslog(syslog.LOG_NOTICE,
                       "This system is missing one or more subscriptions. " +
                        "Please run subscription-manager for more information.")
        elif status == RHSM_PARTIALLY_VALID:
            log_syslog(syslog.LOG_NOTICE,
                       "This system is missing one or more subscriptions " +
                       "to fully cover its products. " +
                       "Please run subscription-manager for more information.")
        elif status == RHSM_WARNING:
            log_syslog(syslog.LOG_NOTICE,
                       "This system's subscriptions are about to expire. " +
                       "Please run subscription-manager for more information.")
        elif status == RHN_CLASSIC:
            log_syslog(syslog.LOG_INFO,
                       get_branding().RHSMD_REGISTERED_TO_OTHER)
        elif status == RHSM_REGISTRATION_REQUIRED:
            log_syslog(syslog.LOG_NOTICE,
                       "In order for Subscription Manager to provide your " +
                       "system with updates, your system must be registered " +
                       "with the Customer Portal. Please enter your Red Hat " +
                       "login to ensure your system is up-to-date.")

        # Return an exit code for the program. having valid entitlements is
        # good, so it gets an exit status of 0.
        return status

    # we are not running from cron here, so unset the excepthook
    # though, we may be running from cli, or as a dbus activation. For
    # cli, we should traceback. For dbus, we should try to log it and
    # raise dbus exception?
    sys.excepthook = sys.__excepthook__

    system_bus = dbus.SystemBus()
    loop = ga_GObject.MainLoop()
    checker = StatusChecker(system_bus, options.keep_alive, force_signal, loop)

    if options.immediate:
        checker.entitlement_status_changed(force_signal)

    loop.run()
コード例 #20
0
ファイル: cli.py プロジェクト: beav/subscription-manager
 def __init__(self, name="cli", short_desc=None):
     self.shortdesc = short_desc
     self.name = name
     self.parser = OptionParser(usage=self._get_usage(), description=self.shortdesc)
     self._define_custom_opts(self.parser)
コード例 #21
0
class MigrationEngine(object):
    def __init__(self):
        self.rhncfg = initUp2dateConfig()
        self.rhsmcfg = rhsm.config.initConfig()

        self.proxy_host = None
        self.proxy_port = None
        self.proxy_user = None
        self.proxy_pass = None

        self.cp = None
        self.db = ProductDatabase()

        self.parser = OptionParser(usage=USAGE, formatter=WrappedIndentedHelpFormatter())
        self.add_parser_options()

    def add_parser_options(self):
        self.parser.add_option(
            "-f", "--force", action="store_true", default=False, help=_("ignore channels not available on RHSM")
        )
        self.parser.add_option(
            "-g",
            "--gui",
            action="store_true",
            default=False,
            dest="gui",
            help=_("launch the GUI tool to attach subscriptions, instead of auto-attaching"),
        )
        self.parser.add_option(
            "-n",
            "--no-auto",
            action="store_true",
            default=False,
            dest="noauto",
            help=_("don't execute the auto-attach option while registering with subscription manager"),
        )
        self.parser.add_option(
            "-s",
            "--servicelevel",
            dest="servicelevel",
            help=_(
                "service level to follow when attaching subscriptions, for no service " 'level use --servicelevel=""'
            ),
        )
        self.parser.add_option(
            "--serverurl", dest="serverurl", help=_("specify the subscription management server to migrate to")
        )
        self.parser.add_option("--redhat-user", dest="redhatuser", help=_("specify the Red Hat user name"))
        self.parser.add_option("--redhat-password", dest="redhatpassword", help=_("specify the Red Hat password"))
        self.parser.add_option(
            "--subscription-service-user", dest="subserviceuser", help=_("specify the subscription service user name")
        )
        self.parser.add_option(
            "--subscription-service-password",
            dest="subservicepassword",
            help=_("specify the subscription service password"),
        )
        # See BZ 915847 - some users want to connect to RHN with a proxy but to RHSM without a proxy
        self.parser.add_option(
            "--no-proxy",
            action="store_true",
            dest="noproxy",
            help=_("don't use RHN proxy settings with subscription management server"),
        )
        self.parser.add_option("--org", dest="org", help=_("organization to register to"))
        self.parser.add_option("--environment", dest="environment", help=_("environment to register to"))

    def validate_options(self):
        if self.options.servicelevel and self.options.noauto:
            system_exit(1, _("The --servicelevel and --no-auto options cannot be used together."))

    def authenticate(self, username, password, user_prompt, pw_prompt):
        if not username:
            username = raw_input(user_prompt).strip()

        if not password:
            password = getpass.getpass(prompt=pw_prompt)

        return UserCredentials(username, password)

    def is_hosted(self):
        hostname = self.rhsmcfg.get("server", "hostname")
        if re.search("subscription\.rhn\.(.*\.)*redhat\.com", hostname):
            return True  # re.search doesn't return a boolean
        else:
            return False

    def get_auth(self):
        self.rhncreds = self.authenticate(
            self.options.redhatuser, self.options.redhatpassword, _("Red Hat username: "******"Red Hat password: "******"Subscription Service username: "******"Subscription Service password: "******"enableProxy"]:
            http_proxy = self.rhncfg["httpProxy"]
            if http_proxy[:7] == "http://":
                http_proxy = http_proxy[7:]
            try:
                self.proxy_host, self.proxy_port = http_proxy.split(":")
            except ValueError, e:
                log.exception(e)
                system_exit(1, _("Unable to read RHN proxy settings."))

            if self.rhncfg["enableProxyAuth"]:
                self.proxy_user = self.rhncfg["proxyUser"]
                self.proxy_pass = self.rhncfg["proxyPassword"]

            log.info("Using proxy %s:%s" % (self.proxy_host, self.proxy_port))
            if self.options.noproxy:
                # If the user doesn't want to use a proxy to connect to their subscription
                # management server, then remove any proxy information that may have crept in.
                self.rhsmcfg.set("server", "proxy_hostname", "")
                self.rhsmcfg.set("server", "proxy_port", "")
                self.rhsmcfg.set("server", "proxy_user", "")
                self.rhsmcfg.set("server", "proxy_password", "")
            else:
                self.rhsmcfg.set("server", "proxy_hostname", self.proxy_host)
                self.rhsmcfg.set("server", "proxy_port", self.proxy_port)
                self.rhsmcfg.set("server", "proxy_user", self.proxy_user or "")
                self.rhsmcfg.set("server", "proxy_password", self.proxy_pass or "")
            self.rhsmcfg.save()