Hacked By AnonymousFox

Current Path : /usr/sbin/
Upload File :
Current File : //usr/sbin/rhnreg_ks-3.6

#!/usr/libexec/platform-python
#
# Registration client for the Spacewalk for useage with kickstart
# Copyright (c) 1999--2020 Red Hat, Inc.  Distributed under GPLv2.
#
# Authors:
#       Adrian Likins <alikins@redhat.com>
#       James Bowes <jbowes@redhat.com>
#
#  see the output of "--help" for the valid options.
#
#  The contact info is in the form or a "key: value" one per line.
#  valid keys are:
#       title, first_name, last_name, company,
#       position, address1, address2, city, state, zip,
#       country, phone, fax, contact_email, contact_mail,
#       contact_phone, contact_fax, contact_special,
#       contact_newsletter
#
#
#

import sys
import os
from rhn.connections import idn_puny_to_unicode
from rhn.i18n import bstr, sstr

import gettext
t = gettext.translation('rhn-client-tools', fallback=True)
# Python 3 translations don't have a ugettext method
if not hasattr(t, 'ugettext'):
    t.ugettext = t.gettext
_ = t.ugettext

from up2date_client import rhnreg
from up2date_client import hardware
from up2date_client import pkgUtils
from up2date_client import up2dateErrors
from up2date_client import rhncli
from up2date_client.pmPlugin import PM_PLUGIN_NAME, PM_PLUGIN_CONF


class RegisterKsCli(rhncli.RhnCli):

    def __init__(self):
        super(RegisterKsCli, self).__init__()

        self.optparser.add_option("--profilename", action="store",
            help=_("Specify a profilename")),
        self.optparser.add_option("--systemorgid", action="store",
            help=_("Specify an organizational id for this system")),
        self.optparser.add_option("--serverUrl", action="store",
            help=_("Specify a url to use as a server")),
        self.optparser.add_option("--sslCACert", action="store",
            help=_("Specify a file to use as the ssl CA cert")),
        self.optparser.add_option("--activationkey", action="store",
            help=_("Specify an activation key")),
        self.optparser.add_option("--contactinfo", action="store_true",
            default=False, help=_("[Deprecated] Read contact info from stdin")),
        self.optparser.add_option("--hardware", dest="nohardware", action="store_false",
            default=True, help=_("Probe and upload hardware info [deprecated]")),
        self.optparser.add_option("--packages", dest="nopackages", action="store_false",
            default=True, help=_("Profile and upload package info [deprecated]")),
        self.optparser.add_option("--virtinfo", dest="novirtinfo", action="store_false",
            default=True, help=_("Upload virtualization info [deprecated]")),
        self.optparser.add_option("--norhnsd", action="store_true",
            default=False, help=_("Do not start rhnsd after completion")),
        self.optparser.add_option("--strict-edition", action="store_true",
            default=False, help=_("Do not start registration if edition does not match the key")),
        self.optparser.add_option("--migrate-silently", dest='silent_migration', action="store_true",
            default=False, help=_("Do not start interactive prompts for user, "
                                  "start migration to different edition automatically")),
        self.optparser.add_option("--force", action="store_true", default=False,
            help=_("Register the system even if it is already registered")),
        self.optparser.add_option('--edition', action='store',
            help='Specify one of the supported editions: solo, shared, admin',
            choices=['solo', 'shared', 'admin', 'auto'],
            default='auto'),

    def main(self):

        if self.options.serverUrl:
            rhnreg.cfg.set("serverURL", self.options.serverUrl)

        if self.options.sslCACert:
            rhnreg.cfg.set("sslCACert", self.options.sslCACert)

        if not self.options.activationkey:
            print(_("An activationkey is required "
                    "to register a system."))
            sys.exit(-1)

        if rhnreg.registered() and not self.options.force:
            print(_("This system is already registered. Use --force to override"))
            sys.exit(-1)

        rhnreg.getCaps()

        if not self.options.nopackages:
            getArch = 0
            if rhnreg.cfg['supportsExtendedPackageProfile']:
                getArch = 1
            packageList = pkgUtils.getInstalledPackageList(getArch=getArch)
        else:
            packageList = []


        hardwareList = hardware.Hardware()

        if self.options.profilename:
            profilename = self.options.profilename
        else:
            profilename = RegisterKsCli.__generateProfileName(hardwareList)

        other = {}
        if self.options.systemorgid:
            other['org_id'] = self.options.systemorgid

        # Try to get the virt uuid and put it in "other".
        (virt_uuid, virt_type) = rhnreg.get_virt_info()
        if not virt_uuid is None:
            other['virt_uuid'] = virt_uuid
            other['virt_type'] = virt_type

        rhnreg.checkLicenseKey(self.options.activationkey,
                               self.options.strict_edition,
                               self.options.silent_migration)

        try:
            systemId = rhnreg.registerSystem(
                profileName=profilename,
                token=self.options.activationkey,
                other=other,
                edition=self.options.edition
            )
            # we run rhn_check below, no need to ask for JWT and Rollout here
        except (up2dateErrors.AuthenticationTicketError,
                up2dateErrors.RhnUuidUniquenessError,
                up2dateErrors.CommunicationError,
                up2dateErrors.AuthenticationOrAccountCreationError):
            e = sys.exc_info()[1]
            print("%s" % e.errmsg)
            sys.exit(1)

        # collect hardware info, inluding hostname
        if not self.options.nohardware:
            rhnreg.sendHardware(systemId, hardwareList)

        if not self.options.nopackages:
            rhnreg.sendPackages(systemId, packageList)

        if self.options.contactinfo:
            print(_("Warning: --contactinfo option has been deprecated. "
                    "Please login to the server web user "
                    "Interface and update your contactinfo. "))

        # write out the new id
        rhnreg.writeSystemId(bstr(systemId))

        # assume successful communication with server
        # remember to save the config options
        rhnreg.cfg.save()

        # Send virtualization information to the server.  We must do this
        # *after* writing out the system id.
        if not self.options.novirtinfo:
            rhnreg.sendVirtInfo(systemId)

        # do this after writing out system id, bug #147513
        if not self.options.norhnsd:
            rhnreg.startRhnsd()

        try:
            present, conf_changed = rhnreg.pluginEnable()
            if not present:
                sys.stderr.write(sstr(_("Warning: %s is not present, could not enable it.") % PM_PLUGIN_NAME))
        except IOError:
            e = sys.exc_info()[1]
            sys.stderr.write(sstr(_("Warning: Could not open %s\n%s is not enabled.\n") % (PM_PLUGIN_CONF, PM_PLUGIN_NAME) + e.errmsg))
        return RegisterKsCli.__runRhnCheck(self.options.verbose, allowTransition=True)

    @staticmethod
    def __generateProfileName(hardwareList):
        hostname = None
        ipaddr = ip6addr = None
        profileName = None
        for hw in hardwareList:
            if hw['class'] == 'NETINFO':
                hostname = hw.get('hostname')
                ipaddr = hw.get('ipaddr')
                ip6addr = hw.get('ipaddr6')

        if hostname:
            profileName = idn_puny_to_unicode(hostname)
        elif ipaddr:
            profileName = ipaddr
        elif ip6addr:
            profileName = ip6addr

        if not profileName:
            print(_("A profilename was not specified, "\
                    "and hostname and IP address could not be determined "\
                    "to use as a profilename, please specify one."))
            sys.exit(-1)

        return profileName

    @staticmethod
    def __runRhnCheck(verbose, allowTransition):
        cmd = "/usr/sbin/rhn_check"
        if verbose:
            cmd += ' -' + ('v' * verbose)
        if allowTransition:
            cmd += ' --allow-transition'
        ret = os.system(cmd)
        return ret >> 8


if __name__ == "__main__":
    cli = RegisterKsCli()
    cli.run()

Hacked By AnonymousFox1.0, Coded By AnonymousFox