Get princial details

    CLI Example:

    .. code-block:: bash

        salt 'kdc.example.com' kerberos.get_principal root/admin
5178
def get_principal(name):
    '''
    
    '''
    ret = {}

    cmd = __execute_kadmin('get_principal {0}'.format(name))

    if cmd['retcode'] != 0 or cmd['stderr']:
        ret['comment'] = cmd['stderr'].splitlines()[-1]
        ret['result'] = False

        return ret

    for i in cmd['stdout'].splitlines()[1:]:
        (prop, val) = i.split(':', 1)

        ret[prop] = val

    return ret
1076112
def get_dc_owner(raises, mask_if_self):
    
    try:
        from pwd import getpwuid
        owner_uid = os.stat('/dev/console').st_uid
        self_uid  = os.getuid()
        if mask_if_self and owner_uid == self_uid:
            return "<self>"
        owner_name = getpwuid(owner_uid).pw_name
        return owner_name
    except Exception as e:
        if raises:
            raise e
        else:
            return str(e)
595312
def get_kerberos_ticket(username, password):
        

        cache = "/tmp/ion-%s" % uuid.uuid4()

        logger.debug("Setting KRB5CCNAME to 'FILE:{}'".format(cache))
        os.environ["KRB5CCNAME"] = "FILE:" + cache

        try:
            realm = settings.CSL_REALM
            kinit = pexpect.spawnu("/usr/bin/kinit {}@{}".format(username, realm), timeout=settings.KINIT_TIMEOUT)
            kinit.expect(":")
            kinit.sendline(password)
            returned = kinit.expect([pexpect.EOF, "password:"])
            if returned == 1:
                logger.debug("Password for {}@{} expired, needs reset".format(username, realm))
                return "reset"
            kinit.close()
            exitstatus = kinit.exitstatus
        except pexpect.TIMEOUT:
            KerberosAuthenticationBackend.kinit_timeout_handle(username, realm)
            exitstatus = 1

        if exitstatus != 0:
            try:
                realm = settings.AD_REALM
                kinit = pexpect.spawnu("/usr/bin/kinit {}@{}".format(username, realm), timeout=settings.KINIT_TIMEOUT)
                kinit.expect(":")
                kinit.sendline(password)
                returned = kinit.expect([pexpect.EOF, "password:"])
                if returned == 1:
                    return False
                kinit.close()
                exitstatus = kinit.exitstatus
            except pexpect.TIMEOUT:
                KerberosAuthenticationBackend.kinit_timeout_handle(username, realm)
                exitstatus = 1

        if "KRB5CCNAME" in os.environ:
            subprocess.check_call(['kdestroy', '-c', os.environ["KRB5CCNAME"]])
            del os.environ["KRB5CCNAME"]

        if exitstatus == 0:
            logger.debug("Kerberos authorized {}@{}".format(username, realm))
            return True
        else:
            logger.debug("Kerberos failed to authorize {}".format(username))
            return False
64859
def get_merkle_root(block_representation, coin_symbol='btc', api_key=None):
    '''
    
    '''
    return get_block_overview(block_representation=block_representation,
            coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['mrkl_root']
904761
def _get_credentials():
    '''
    
    '''
    ret = {
        'user': False,
        'passwd': False
    }

    # Loop through opts, grains, and pillar
    # Return the first acceptable configuration found
    for item in ret:
        for struct in [__opts__, __grains__, __pillar__]:
            # Look for the config key
            # Support old-style config format and new
            for config_key in __valid_configs[item]:
                value = salt.utils.data.traverse_dict_and_list(
                    struct,
                    config_key,
                    None)
                if value:
                    ret[item] = value
                    break
    return ret['user'], ret['passwd']
1252910
def get_key_auth_cb(key_filepath):
    """"""

    def auth_cb(ssh):
        key = ssh_pki_import_privkey_file(key_filepath)
        ssh.userauth_publickey(key)

    return auth_cb
262810
def chgid(name, gid):
    '''
    
    '''
    pre_info = info(name)
    if not pre_info:
        raise CommandExecutionError(
            'User \'{0}\' does not exist'.format(name)
        )
    if gid == pre_info['gid']:
        return True
    cmd = ['usermod', '-g', gid, name]
    __salt__['cmd.run'](cmd, python_shell=False)
    return info(name).get('gid') == gid
692520
def system_info(host=None,
                admin_username=None, admin_password=None,
                module=None):
    '''
    
    '''
    cmd = __execute_ret('getsysinfo', host=host,
                        admin_username=admin_username,
                        admin_password=admin_password,
                        module=module)

    if cmd['retcode'] != 0:
        log.warning('racadm returned an exit code of %s', cmd['retcode'])
        return cmd

    return __parse_drac(cmd['stdout'])
655432
def _get_credentials(username=None, password=None, dbhost=None):
    """"""

    # Database salt
    system_config = dbhost.objectmodels['systemconfig'].find_one({
        'active': True
    })

    try:
        salt = system_config.salt.encode('ascii')
    except (KeyError, AttributeError):
        log('No systemconfig or it is without a salt! '
            'Reinstall the system provisioning with'
            'hfos_manage.py install provisions -p system')
        sys.exit(3)

    if username is None:
        username = _ask("Please enter username: ")
    else:
        username = username

    if password is None:
        password = _ask_password()
    else:
        password = password

    try:
        password = password.encode('utf-8')
    except UnicodeDecodeError:
        password = password

    passhash = hashlib.sha512(password)
    passhash.update(salt)

    return username, passhash.hexdigest()
747365
def get_user_cmd(node_dict):
    """"""
    key_lu = {"q": ["quit", True], "r": ["run", True],
              "s": ["stop", True], "u": ["update", True],
              "c": ["connect", True], "d": ["details", True]}
    ui_cmd_bar()
    cmd_valid = False
    input_flush()
    with term.cbreak():
        while not cmd_valid:
            val = input_by_key()
            cmd_name, cmd_valid = key_lu.get(val.lower(), ["invalid", False])
            if not cmd_valid:
                ui_print(" - {0}Invalid Entry{1}".format(C_ERR, C_NORM))
                sleep(0.5)
                ui_cmd_bar()
    return cmd_name
1315985
def get_gateway_info(self):
        
        def process_result(result):
            return GatewayInfo(result)

        return Command('get',
                       [ROOT_GATEWAY, ATTR_GATEWAY_INFO],
                       process_result=process_result)
208730
def info(name, root=None):
    '''
    
    '''
    if root is not None:
        getspnam = functools.partial(_getspnam, root=root)
    else:
        getspnam = functools.partial(spwd.getspnam)

    try:
        data = getspnam(name)
        ret = {
            'name': data.sp_namp if hasattr(data, 'sp_namp') else data.sp_nam,
            'passwd': data.sp_pwdp if hasattr(data, 'sp_pwdp') else data.sp_pwd,
            'lstchg': data.sp_lstchg,
            'min': data.sp_min,
            'max': data.sp_max,
            'warn': data.sp_warn,
            'inact': data.sp_inact,
            'expire': data.sp_expire}
    except KeyError:
        return {
            'name': '',
            'passwd': '',
            'lstchg': '',
            'min': '',
            'max': '',
            'warn': '',
            'inact': '',
            'expire': ''}
    return ret
1343290
def find_credentials():
    '''
    
    '''
    usernames = [__pillar__['proxy'].get('admin_username', 'root')]
    if 'fallback_admin_username' in __pillar__.get('proxy'):
        usernames.append(__pillar__['proxy'].get('fallback_admin_username'))

    for user in usernames:
        for pwd in __pillar__['proxy']['passwords']:
            r = __salt__['dracr.get_chassis_name'](host=__pillar__['proxy']['host'],
                                                   admin_username=user,
                                                   admin_password=pwd)
            # Retcode will be present if the chassis_name call failed
            try:
                if r.get('retcode', None) is None:
                    DETAILS['admin_username'] = user
                    DETAILS['admin_password'] = pwd
                    __opts__['proxy']['admin_username'] = user
                    __opts__['proxy']['admin_password'] = pwd
                    return (user, pwd)
            except AttributeError:
                # Then the above was a string, and we can return the username
                # and password
                DETAILS['admin_username'] = user
                DETAILS['admin_password'] = pwd
                __opts__['proxy']['admin_username'] = user
                __opts__['proxy']['admin_password'] = pwd
                return (user, pwd)

    log.debug('proxy fx2.find_credentials found no valid credentials, using Dell default')
    return ('root', 'calvin')
435484
def get_service_info(service_instance):
    '''
    
    '''
    try:
        return service_instance.content.about
    except vim.fault.NoPermission as exc:
        log.exception(exc)
        raise salt.exceptions.VMwareApiError(
            'Not enough permissions. Required privilege: '
            '{0}'.format(exc.privilegeId))
    except vim.fault.VimFault as exc:
        log.exception(exc)
        raise salt.exceptions.VMwareApiError(exc.msg)
    except vmodl.RuntimeFault as exc:
        log.exception(exc)
        raise salt.exceptions.VMwareRuntimeError(exc.msg)
1091483
def _get_principal(self, principal_arn):
        
        if ':cert/' in principal_arn:
            certs = [_ for _ in self.certificates.values() if _.arn == principal_arn]
            if len(certs) == 0:
                ()
            principal = certs[0]
            return principal
        else:
            # TODO: search for cognito_ids
            pass
        ()
899721
protected String getOrigin(Principal principal) {

        if (principal instanceof Authentication) {

            Authentication caller = (Authentication) principal;
            StringBuilder builder = new StringBuilder();
            if (caller instanceof OAuth2Authentication) {
                OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) caller;
                builder.append("client=").append(oAuth2Authentication.getOAuth2Request().getClientId());
                if (!oAuth2Authentication.isClientOnly()) {
                    builder.append(", ").append("user=").append(oAuth2Authentication.getName());
                }
            }
            else {
                builder.append("caller=").append(caller.getName());
            }


            if (caller.getDetails() != null) {
                builder.append(", details=(");
                try {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> map =
                        JsonUtils.readValue((String)caller.getDetails(), new TypeReference<Map<String,Object>>(){});
                    if (map.containsKey("remoteAddress")) {
                        builder.append("remoteAddress=").append(map.get("remoteAddress")).append(", ");
                    }
                    builder.append("type=").append(caller.getDetails().getClass().getSimpleName());
                } catch (Exception e) {
                    // ignore
                    builder.append(caller.getDetails());
                }
                appendTokenDetails(caller, builder);
                builder.append(")");
            }
            return builder.toString();

        }

        return principal == null ? null : principal.getName();

    }
230803
def parse_authority(cls, authority):
        ''''''
        userinfo, sep, host = authority.partition('@')

        if not sep:
            return '', userinfo
        else:
            return userinfo, host