:param str|unicode use_credentials: Enable check of SCM_CREDENTIALS for tuntap client/server.

        :param str|unicode stats_server: Router stats server address to run at.
484355
def set_basic_params(self, use_credentials=None, stats_server=None):
        
        self._set_aliased('use-credentials', use_credentials)
        self._set_aliased('router-stats', stats_server)

        return self
614739
def _build_credentials_tuple(mech, source, user, passwd, extra, database):
    
    if mech != 'MONGODB-X509' and user is None:
        raise ConfigurationError("%s requires a username." % (mech,))
    if mech == 'GSSAPI':
        if source is not None and source != '$external':
            raise ValueError(
                "authentication source must be $external or None for GSSAPI")
        properties = extra.get('authmechanismproperties', {})
        service_name = properties.get('SERVICE_NAME', 'mongodb')
        canonicalize = properties.get('CANONICALIZE_HOST_NAME', False)
        service_realm = properties.get('SERVICE_REALM')
        props = GSSAPIProperties(service_name=service_name,
                                 canonicalize_host_name=canonicalize,
                                 service_realm=service_realm)
        # Source is always $external.
        return MongoCredential(mech, '$external', user, passwd, props, None)
    elif mech == 'MONGODB-X509':
        if passwd is not None:
            raise ConfigurationError(
                "Passwords are not supported by MONGODB-X509")
        if source is not None and source != '$external':
            raise ValueError(
                "authentication source must be "
                "$external or None for MONGODB-X509")
        # user can be None.
        return MongoCredential(mech, '$external', user, None, None, None)
    elif mech == 'PLAIN':
        source_database = source or database or '$external'
        return MongoCredential(mech, source_database, user, passwd, None, None)
    else:
        source_database = source or database or 'admin'
        if passwd is None:
            raise ConfigurationError("A password is required.")
        return MongoCredential(
            mech, source_database, user, passwd, None, _Cache())
137830
def getCPUuse(self):
        
        hz = os.sysconf('SC_CLK_TCK')
        info_dict = {}
        try:
            fp = open(cpustatFile, 'r')
            line = fp.readline()
            fp.close()
        except:
            raise IOError('Failed reading stats from file: %s' % cpustatFile)
        headers = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq', 'steal', 'guest']
        arr = line.split()
        if len(arr) > 1 and arr[0] == 'cpu':
            return dict(zip(headers[0:len(arr)], [(float(t) / hz) for t in arr[1:]]))
        return info_dict
1074406
def set_auth_credentials(username, password):
    
    global _credentials, _dirty

    LOGGER.debug('Setting authentication credentials')
    _credentials = username, password
    _dirty = True
321570
def _use_remote_connection(self, kwargs):
        '''
        
        '''
        kwargs['host'] = kwargs.get('host')
        kwargs['username'] = kwargs.get('username')
        kwargs['password'] = kwargs.get('password')
        if kwargs['host'] is None or \
           kwargs['username'] is None or \
           kwargs['password'] is None:
            return False
        else:
            return True
212550
def server_by_name(name, profile=None, **kwargs):
    '''
    
    '''
    conn = _auth(profile, **kwargs)
    return conn.server_by_name(name)
1172195
def _authenticate_plain(credentials, sock_info):
    
    source = credentials.source
    username = credentials.username
    password = credentials.password
    payload = ('\x00%s\x00%s' % (username, password)).encode('utf-8')
    cmd = SON([('saslStart', 1),
               ('mechanism', 'PLAIN'),
               ('payload', Binary(payload)),
               ('autoAuthorize', 1)])
    sock_info.command(source, cmd)
684861
def set_snmpv3_service(authentication_type = Credential::AuthenticationType::NOAUTH, username = nil, password = nil, privacy_type = Credential::PrivacyType::NOPRIV, privacy_password = nil)
      self.authentication_type = authentication_type
      self.user_name           = username
      self.password            = password
      self.privacy_type        = privacy_type
      self.privacy_password    = privacy_password
      self.service             = Credential::Service::SNMPV3
    end
103844
def set_credentials(self, username, password=None, region=None,
            tenant_id=None, authenticate=False):
        
        self.api_key = None
        super(RaxIdentity, self).set_credentials(username, password=password,
                region=region, tenant_id=tenant_id, authenticate=authenticate)
1165016
def alias(self, aliases, stats):
        
        login = email = None
        if stats is None:
            return
        # Attempt to use alias directly from the config section
        try:
            config = dict(Config().section(stats))
            try:
                email = config["email"]
            except KeyError:
                pass
            try:
                login = config["login"]
            except KeyError:
                pass
        except (ConfigFileError, NoSectionError):
            pass
        # Check for aliases specified in the email string
        if aliases is not None:
            try:
                aliases = dict([
                    re.split(r"\s*:\s*", definition, 1)
                    for definition in re.split(r"\s*;\s*", aliases.strip())])
            except ValueError:
                raise ConfigError(
                    "Invalid alias definition: '{0}'".format(aliases))
            if stats in aliases:
                if "@" in aliases[stats]:
                    email = aliases[stats]
                else:
                    login = aliases[stats]
        # Update login/email if alias detected
        if email is not None:
            self.email = email
            log.info("Using email alias '{0}' for '{1}'".format(email, stats))
            if login is None:
                login = email.split("@")[0]
        if login is not None:
            self.login = login
            log.info("Using login alias '{0}' for '{1}'".format(login, stats))
1241790
def authenticate_credentials(self, request, access_token):
        

        try:
            token = oauth2_provider.oauth2.models.AccessToken.objects.select_related('user')
            # provider_now switches to timezone aware datetime when
            # the oauth2_provider version supports to it.
            token = token.get(token=access_token, expires__gt=provider_now())
        except oauth2_provider.oauth2.models.AccessToken.DoesNotExist:
            raise exceptions.AuthenticationFailed('Invalid token')

        user = token.user

        if not user.is_active:
            msg = 'User inactive or deleted: %s' % user.username
            raise exceptions.AuthenticationFailed(msg)

        return (user, token)
1297411
def _connect_su(spec):
    
    return {
        'method': 'su',
        'enable_lru': True,
        'kwargs': {
            'username': spec.become_user(),
            'password': spec.become_pass(),
            'python_path': spec.python_path(),
            'su_path': spec.become_exe(),
            'connect_timeout': spec.timeout(),
            'remote_name': get_remote_name(spec),
        }
    }
573569
def init_sts_session(profile_name, credentials, duration = 28800, session_name = None, save_creds = True):
    
    # Set STS arguments
    sts_args = {
        'DurationSeconds': duration
    }
    # Prompt for MFA code if MFA serial present
    if 'SerialNumber' in credentials and credentials['SerialNumber']:
        if not credentials['TokenCode']:
            credentials['TokenCode'] = prompt_4_mfa_code()
            if credentials['TokenCode'] == 'q':
                credentials['SerialNumber'] = None
        sts_args['TokenCode'] = credentials['TokenCode']
        sts_args['SerialNumber'] = credentials['SerialNumber']
    # Init session
    sts_client = boto3.session.Session(credentials['AccessKeyId'], credentials['SecretAccessKey']).client('sts')
    sts_response = sts_client.get_session_token(**sts_args)
    if save_creds:
        # Move long-lived credentials if needed
        if not profile_name.endswith('-nomfa') and credentials['AccessKeyId'].startswith('AKIA'):
            write_creds_to_aws_credentials_file(profile_name + '-nomfa', credentials)
        # Save STS values in the .aws/credentials file
        write_creds_to_aws_credentials_file(profile_name, sts_response['Credentials'])
    return sts_response['Credentials']
1323794
def __display_server(self, server):
        
        # Display the Glances client for the selected server
        logger.debug("Selected server {}".format(server))

        # Connection can take time
        # Display a popup
        self.screen.display_popup(
            'Connect to {}:{}'.format(server['name'], server['port']), duration=1)

        # A password is needed to access to the server's stats
        if server['password'] is None:
            # First of all, check if a password is available in the [passwords] section
            clear_password = self.password.get_password(server['name'])
            if (clear_password is None or self.get_servers_list()
                    [self.screen.active_server]['status'] == 'PROTECTED'):
                # Else, the password should be enter by the user
                # Display a popup to enter password
                clear_password = self.screen.display_popup(
                    'Password needed for {}: '.format(server['name']), is_input=True)
            # Store the password for the selected server
            if clear_password is not None:
                self.set_in_selected('password', self.password.sha256_hash(clear_password))

        # Display the Glance client on the selected server
        logger.info("Connect Glances client to the {} server".format(server['key']))

        # Init the client
        args_server = self.args

        # Overwrite connection setting
        args_server.client = server['ip']
        args_server.port = server['port']
        args_server.username = server['username']
        args_server.password = server['password']
        client = GlancesClient(config=self.config, args=args_server, return_to_browser=True)

        # Test if client and server are in the same major version
        if not client.login():
            self.screen.display_popup(
                "Sorry, cannot connect to '{}'\n"
                "See '{}' for more details".format(server['name'], LOG_FILENAME))

            # Set the ONLINE status for the selected server
            self.set_in_selected('status', 'OFFLINE')
        else:
            # Start the client loop
            # Return connection type: 'glances' or 'snmp'
            connection_type = client.serve_forever()

            try:
                logger.debug("Disconnect Glances client from the {} server".format(server['key']))
            except IndexError:
                # Server did not exist anymore
                pass
            else:
                # Set the ONLINE status for the selected server
                if connection_type == 'snmp':
                    self.set_in_selected('status', 'SNMP')
                else:
                    self.set_in_selected('status', 'ONLINE')

        # Return to the browser (no server selected)
        self.screen.active_server = None
711031
def _authenticate_client(self, client, secret):
        
        client_s = str.join(':', [client, secret])
        credentials = base64.b64encode(client_s.encode('utf-8')).decode('utf-8')

        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Cache-Control': 'no-cache',
            'Authorization': 'Basic ' + credentials
            }
        params = {
            'client_id': client,
            'grant_type': 'client_credentials'
            }
        uri = self.uri + '/oauth/token'

        logging.debug("URI=" + str(uri))
        logging.debug("HEADERS=" + str(headers))
        logging.debug("BODY=" + str(params))

        response = requests.post(uri, headers=headers, params=params)
        if response.status_code == 200:
            logging.debug("RESPONSE=" + str(response.json()))
            return response.json()
        else:
            logging.warning("Failed to authenticate as %s" % (client))
            response.raise_for_status()
393569
def get_auth():
    
    import getpass
    from requests.auth import HTTPDigestAuth
    #This binds raw_input to input for Python 2
    input_func = input
    try:
        input_func = raw_input
    except NameError:
        pass
    uname = input_func("MODSCAG Username:")
    pw = getpass.getpass("MODSCAG Password:")
    auth = HTTPDigestAuth(uname, pw)
    #wget -A'h8v4*snow_fraction.tif' --user=uname --password=pw
    return auth
1326318
def _init_server_authentication(self, ssl_verify: OpenSslVerifyEnum, ssl_verify_locations: Optional[str]) -> None:
        
        self._ssl_ctx.set_verify(ssl_verify.value)
        if ssl_verify_locations:
            # Ensure the file exists
            with open(ssl_verify_locations):
                pass
            self._ssl_ctx.load_verify_locations(ssl_verify_locations)