Getting the username/password for host from .netrc filie
559000
def getUserPassword(host='www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca'):
    "
    if os.access(os.path.join(os.environ.get('HOME','/'),".netrc"),os.R_OK):
        auth=netrc.netrc().authenticators(host)
    else:
        auth=False
    if not auth:
        sys.stdout.write("CADC Username: ")
        username=sys.stdin.readline().strip('\n')
        password=getpass.getpass().strip('\n')
    else:
        username=auth[0]
        password=auth[2]
    return (username,password)
252579
def get_host_name():
    

    if sys.platform == 'win32':
        host = os.getenv('COMPUTERNAME')
    else:
        host = os.uname()[1]


    return host
619781
def _determine_username(self, ip):
        """"""
        ssh = subprocess.Popen([
            "ssh",
            "-o", "UserKnownHostsFile=/dev/null",
            "-o", "StrictHostKeyChecking=no",
            "root@%s" % ip],
            stdin=subprocess.DEVNULL,
            stdout=subprocess.PIPE,
            stderr=subprocess.DEVNULL)
        first_line = ssh.stdout.readline()
        ssh.kill()
        ssh.wait()
        if first_line:
            match = re.search(
                r"Please login as the user \"(\w+)\" rather than "
                r"the user \"root\".", first_line.decode('utf-8'))
            if match:
                return match.groups()[0]
        else:
            return None
570008
def authenticate_through_netrc(path=None):
    
    errors = []
    netrc_machine = 'coursera-dl'
    paths = [path] if path else get_config_paths("netrc")
    for path in paths:
        try:
            logging.debug('Trying netrc file %s', path)
            auths = netrc.netrc(path).authenticators(netrc_machine)
        except (IOError, netrc.NetrcParseError) as e:
            errors.append(e)
        else:
            if auths is None:
                errors.append('Didn\'t find any credentials for ' +
                              netrc_machine)
            else:
                return auths[0], auths[2]

    error_messages = '\n'.join(str(e) for e in errors)
    raise CredentialsError(
        'Did not find valid netrc file:\n' + error_messages +
        '\nPlease run this command: chmod og-rw ~/.netrc')
892660
def _get_conn(ret=None):
    '''
    
    '''
    _options = _get_options(ret)
    dsn = _options.get('dsn')
    user = _options.get('user')
    passwd = _options.get('passwd')

    return pyodbc.connect('DSN={0};UID={1};PWD={2}'.format(
            dsn,
            user,
            passwd))
171646
def get_credentials_for_url(url, opts, force_user=None):
    
    creds = None
    verbose = int(opts.get("verbose"))
    force_prompt = opts.get("prompt", False)
    allow_prompt = not opts.get("no_prompt", True)
    allow_keyring = not opts.get("no_keyring", False) and not force_user
    allow_netrc = not opts.get("no_netrc", False) and not force_user

    # print("get_credentials_for_url", force_user, allow_prompt)
    if force_user and not allow_prompt:
        raise RuntimeError(
            "Cannot get credentials for a distinct user ({}) from keyring or .netrc and "
            "prompting is disabled.".format(force_user)
        )

    # Lookup our own pyftpsync 1.x credential store. This is deprecated with 2.x
    home_path = os.path.expanduser("~")
    file_path = os.path.join(home_path, DEFAULT_CREDENTIAL_STORE)
    if os.path.isfile(file_path):
        raise RuntimeError(
            "Custom password files are no longer supported. Delete {} and use .netrc instead.".format(
                file_path
            )
        )

    # Query keyring database
    if creds is None and keyring and allow_keyring:
        try:
            # Note: we pass the url as `username` and username:password as `password`
            c = keyring.get_password("pyftpsync", url)
            if c is not None:
                creds = c.split(":", 1)
                write(
                    "Using credentials from keyring('pyftpsync', '{}'): {}:***.".format(
                        url, creds[0]
                    )
                )
            else:
                if verbose >= 4:
                    write(
                        "No credentials found in keyring('pyftpsync', '{}').".format(
                            url
                        )
                    )
        #        except keyring.errors.TransientKeyringError:
        except Exception as e:
            # e.g. user clicked 'no'
            write_error("Could not get password from keyring {}".format(e))

    # Query .netrc file
    #     print(opts)
    if creds is None and allow_netrc:
        try:
            authenticators = None
            authenticators = netrc.netrc().authenticators(url)
        except CompatFileNotFoundError:
            if verbose >= 4:
                write("Could not get password (no .netrc file).")
        except Exception as e:
            write_error("Could not read .netrc: {}.".format(e))

        if authenticators:
            creds = (authenticators[0], authenticators[2])
            write("Using credentials from .netrc file: {}:***.".format(creds[0]))
        else:
            if verbose >= 4:
                write("Could not find entry for '{}' in .netrc file.".format(url))

    # Prompt for password if we don't have credentials yet, or --prompt was set.
    if allow_prompt:
        if creds is None:
            creds = prompt_for_password(url)
        elif force_prompt:
            # --prompt was set but we can provide a default for the user name
            creds = prompt_for_password(url, default_user=creds[0])

    return creds
562056
def netrc_from_env() -> Optional[netrc.netrc]:
    
    netrc_env = os.environ.get('NETRC')

    if netrc_env is not None:
        netrc_path = Path(netrc_env)
    else:
        try:
            home_dir = Path.home()
        except RuntimeError as e:  # pragma: no cover
            # if pathlib can't resolve home, it may raise a RuntimeError
            client_logger.debug('Could not resolve home directory when '
                                'trying to look for .netrc file: %s', e)
            return None

        netrc_path = home_dir / (
            '_netrc' if platform.system() == 'Windows' else '.netrc')

    try:
        return netrc.netrc(str(netrc_path))
    except netrc.NetrcParseError as e:
        client_logger.warning('Could not parse .netrc file: %s', e)
    except OSError as e:
        # we couldn't read the file (doesn't exist, permissions, etc.)
        if netrc_env or netrc_path.is_file():
            # only warn if the environment wanted us to load it,
            # or it appears like the default file does actually exist
            client_logger.warning('Could not read .netrc file: %s', e)

    return None
1190486
def format(self):
        """"""
        self._netrc.hosts = dedictify_machines(self.machines)
        rep = ""
        for host in self._netrc.hosts.keys():
            attrs = self._netrc.hosts[host]
            rep += "machine {host}\n\tlogin {attrs[0]}\n".format(host=host,
                                                                 attrs=attrs)
            if attrs[1]:
                rep += "\taccount {attrs[1]}\n".format(attrs=attrs)
            rep += "\tpassword {attrs[2]}\n".format(attrs=attrs)
        for macro in self._netrc.macros.keys():
            rep += "macdef {macro}\n".format(macro=macro)
            for line in self._netrc.macros[macro]:
                rep += line
            rep += "\n"
        return rep
458979
def get_netloc_and_auth(self, netloc, scheme):
        
        if scheme == 'ssh':
            # The --username and --password options can't be used for
            # svn+ssh URLs, so keep the auth information in the URL.
            return super(Subversion, self).get_netloc_and_auth(
                netloc, scheme)

        return split_auth_from_netloc(netloc)
205218
def get_conn():
    '''
    
    '''
    vm_ = get_configured_provider()
    driver = get_driver(Provider.DIMENSIONDATA)

    region = config.get_cloud_config_value(
         'region', vm_, __opts__
    )

    user_id = config.get_cloud_config_value(
        'user_id', vm_, __opts__
    )
    key = config.get_cloud_config_value(
        'key', vm_, __opts__
    )

    if key is not None:
        log.debug('DimensionData authenticating using password')

    return driver(
        user_id,
        key,
        region=region
    )
555078
def _username():
    '''
    
    '''
    if pwd:
        username = pwd.getpwuid(os.getuid()).pw_name
    else:
        username = getpass.getuser()

    return username
49839
def get_credentials(username=None, password=None, netrc=None, use_keyring=False):
    
    if netrc:
        path = None if netrc is True else netrc
        return authenticate_through_netrc(path)

    if not username:
        raise CredentialsError(
            'Please provide a username with the -u option, '
            'or a .netrc file with the -n option.')

    if not password and use_keyring:
        password = keyring.get_password(KEYRING_SERVICE_NAME, username)

    if not password:
        password = getpass.getpass('Coursera password for {0}: '.format(username))
        if use_keyring:
            keyring.set_password(KEYRING_SERVICE_NAME, username, password)

    return username, password
717804
def get_name(self):
        """"""
        if self.given_name is None:
            # Name according to host
            if self.hostname is None:
                name = _("Console")
            else:
                name = self.hostname
            # Adding id to name
            client_id = self.id_['int_id'] + u'/' + self.id_['str_id']
            name = name + u' ' + client_id
        elif self.given_name in ["Pylab", "SymPy", "Cython"]:
            client_id = self.id_['int_id'] + u'/' + self.id_['str_id']
            name = self.given_name + u' ' + client_id
        else:
            name = self.given_name + u'/' + self.id_['str_id']
        return name
580386
def connection_key(self):
        
        return "{host}:{namespace}:{username}".format(host=self.host, namespace=self.namespace, username=self.username)
1313307
def get_name(default: str = 'no name set'):
    
    try:
        with open('/etc/machine-info') as emi:
            contents = emi.read()
    except OSError:
        LOG.exception(
            "Couldn't read /etc/machine-info")
        contents = ''
    for line in contents.split('\n'):
        if line.startswith('PRETTY_HOSTNAME='):
            return '='.join(line.split('=')[1:])
    LOG.warning(f"No PRETTY_HOSTNAME in {contents}, defaulting to {default}")
    try:
        _update_pretty_hostname(default)
    except OSError:
        LOG.exception("Could not write new pretty hostname!")
    return default
398317
def load_name(self, load):
        '''
        
        '''
        if 'eauth' not in load:
            return ''
        fstr = '{0}.auth'.format(load['eauth'])
        if fstr not in self.auth:
            return ''
        try:
            pname_arg = salt.utils.args.arg_lookup(self.auth[fstr])['args'][0]
            return load[pname_arg]
        except IndexError:
            return ''
947196
def _get_credentials(server=None,
                     username=None,
                     password=None):
    '''
    
    '''
    jira_cfg = __salt__['config.merge']('jira', default={})
    if not server:
        server = jira_cfg.get('server')
    if not username:
        username = jira_cfg.get('username')
    if not password:
        password = jira_cfg.get('password')
    return server, username, password