Read a .netrc file and return login/password for LWN.
189822
def get_login_password(site_name="github.com",
                       netrc_file="~/.netrc",
                       git_credential_file="~/.git-credentials"):
    """"""
    try:
        n = netrc.netrc(os.path.expanduser(netrc_file))
    except OSError:
        pass
    else:
        if site_name in n.hosts:
            return n.hosts[site_name][0], n.hosts[site_name][2]

    try:
        with open(os.path.expanduser(git_credential_file)) as f:
            for line in f:
                parsed = parse.urlparse(line.strip())
                if parsed.hostname == site_name:
                    return (parse.unquote(parsed.username),
                            parse.unquote(parsed.password))
    except OSError:
        pass

    return None, None
461144
def vncRequestPassword(self):
        """"""
        if self.factory.password is None:
            log.msg("need a password")
            self.transport.loseConnection()
            return
        self.sendPassword(self.factory.password)
524025
def _get_auth(self, user=None, password=None):
        
        fn = os.path.expanduser(AUTH_FILE)
        if os.path.exists(fn):
            for i, line in enumerate(csv.reader(open(fn))):
                if len(line) != 3:
                    log.warning("Cannot parse line {i} in {fn}".format(**locals()))
                    continue
                hostname, username, pwd = line
                if (hostname in ("", "*", self.host)
                    and (user is None or username == user)):
                    return (username, pwd)
        if user is None:
            user = os.environ.get("AMCAT_USER", os.environ.get("USER"))
        if password is None:
            password = os.environ.get("AMCAT_PASSWORD")
        if user is None or password is None:
            raise Exception("No authentication info for {user}@{self.host} "
                            "from {fn} or AMCAT_USER / AMCAT_PASSWORD "
                            "variables".format(**locals()))
        return user, password
301015
def read(self, *args):
        """"""

        self.log("Beginning new transaction: ", args, lvl=network)
        try:
            sock, msg = args[0], args[1]
            user = password = client = clientuuid = useruuid = requestdata = \
                requestaction = None
            # self.log("", msg)

            clientuuid = self._sockets[sock].clientuuid
        except Exception as e:
            self.log("Receiving error: ", e, type(e), lvl=error)

        if clientuuid in self._flooding:
            return

        try:
            msg = json.loads(msg)
            self.log("Message from client received: ", msg, lvl=network)
        except Exception as e:
            self.log("JSON Decoding failed! %s (%s of %s)" % (msg, e, type(e)))
            return

        try:
            requestcomponent = msg['component']
            requestaction = msg['action']
        except (KeyError, AttributeError) as e:
            self.log("Unpacking error: ", msg, e, type(e), lvl=error)
            return

        if self._check_flood_protection(requestcomponent, requestaction,
                                        clientuuid):
            self.log('Flood protection triggered')
            self._flooding[clientuuid] = time()

        try:
            # TODO: Do not unpickle or decode anything from unsafe events
            requestdata = msg['data']
            if isinstance(requestdata, (dict, list)) and 'raw' in requestdata:
                # self.log(requestdata['raw'], lvl=critical)
                requestdata['raw'] = b64decode(requestdata['raw'])
                # self.log(requestdata['raw'])
        except (KeyError, AttributeError) as e:
            self.log("No payload.", lvl=network)
            requestdata = None

        if requestcomponent == "auth":
            self._handleAuthenticationEvents(requestdata, requestaction,
                                             clientuuid, sock)
            return

        try:
            client = self._clients[clientuuid]
        except KeyError as e:
            self.log('Could not get client for request!', e, type(e), lvl=warn)
            return

        if requestcomponent in self.anonymous_events and requestaction in \
            self.anonymous_events[requestcomponent]:
            self.log('Executing anonymous event:', requestcomponent,
                     requestaction)
            try:
                self._handleAnonymousEvents(requestcomponent, requestaction,
                                            requestdata, client)
            except Exception as e:
                self.log("Anonymous request failed:", e, type(e), lvl=warn,
                         exc=True)
            return

        elif requestcomponent in self.authorized_events:
            try:
                useruuid = client.useruuid
                self.log("Authenticated operation requested by ",
                         useruuid, client.config, lvl=network)
            except Exception as e:
                self.log("No useruuid!", e, type(e), lvl=critical)
                return

            self.log('Checking if user is logged in', lvl=verbose)

            try:
                user = self._users[useruuid]
            except KeyError:
                if not (requestaction == 'ping' and requestcomponent == 'hfos.ui.clientmanager'):
                    self.log("User not logged in.", lvl=warn)

                return

            self.log('Handling event:', requestcomponent, requestaction, lvl=verbose)
            try:
                self._handleAuthorizedEvents(requestcomponent, requestaction,
                                             requestdata, user, client)
            except Exception as e:
                self.log("User request failed: ", e, type(e), lvl=warn,
                         exc=True)
        else:
            self.log('Invalid event received:', requestcomponent, requestaction, lvl=warn)
1172042
def cli(env, identifier):
    """"""

    nw_mgr = SoftLayer.NetworkManager(env.client)
    result = nw_mgr.get_nas_credentials(identifier)
    table = formatting.Table(['username', 'password'])
    table.add_row([result.get('username', 'None'),
                   result.get('password', 'None')])
    env.fout(table)
700434
def read_authentication_config (self):
        """"""
        section = "authentication"
        password_fields = []
        if self.has_option(section, "entry"):
            for val in read_multiline(self.get(section, "entry")):
                auth = val.split()
                if len(auth) == 3:
                    self.config.add_auth(pattern=auth[0], user=auth[1],
                                         password=auth[2])
                    password_fields.append("entry/%s/%s" % (auth[0], auth[1]))
                elif len(auth) == 2:
                    self.config.add_auth(pattern=auth[0], user=auth[1])
                else:
                    raise LinkCheckerError(
                       _("missing auth part in entry %(val)r") % {"val": val})
        # read login URL and field names
        if self.has_option(section, "loginurl"):
            val = self.get(section, "loginurl").strip()
            if not (val.lower().startswith("http:") or
                    val.lower().startswith("https:")):
                raise LinkCheckerError(_("invalid login URL `%s'. Only " \
                  "HTTP and HTTPS URLs are supported.") % val)
            self.config["loginurl"] = val
        self.read_string_option(section, "loginuserfield")
        self.read_string_option(section, "loginpasswordfield")
        # read login extra fields
        if self.has_option(section, "loginextrafields"):
            for val in read_multiline(self.get(section, "loginextrafields")):
                name, value = val.split(":", 1)
                self.config["loginextrafields"][name] = value
        self.check_password_readable(section, password_fields)
994807
def cli(ctx, hostname, username, password, config_dir, https):
    """"""
    ctx.is_root = True
    ctx.user_values_entered = False
    ctx.config_dir = os.path.abspath(os.path.expanduser(config_dir))
    ctx.config = load_config(ctx)
    ctx.hostname = hostname
    ctx.username = username
    ctx.password = password
    ctx.https = https

    # Creating the WVA object is deferred as some commands like clearconfig
    # should not require a username/password to perform them
    ctx.wva = None
501496
def userpass(self, dir="ppcoin"):
        """"""

        source = os.path.expanduser("~/.{0}/{0}.conf").format(dir)
        dest = open(source, "r")
        with dest as conf:
            for line in conf:
                if line.startswith("rpcuser"):
                    username = line.split("=")[1].strip()
                if line.startswith("rpcpassword"):
                    password = line.split("=")[1].strip()

        return username, password
348695
def netloc(self):
        """"""
        s = ''
        prefix = ''
        if self.username:
            s += self.username
            prefix = '@'

        if self.password:
            s += ":{password}".format(password=self.password)
            prefix = '@'

        s += "{prefix}{hostloc}".format(prefix=prefix, hostloc=self.hostloc)
        return s
612902
def read(self, name, pwd=None):
        """"""
        with self.open(name, "r", pwd) as fp:
            return fp.read()
557029
def telnet_login(
        self,
        pri_prompt_terminator=r"]\s*$",
        alt_prompt_terminator=r">\s*$",
        username_pattern=r"(?:user:|username|login|user name)",
        pwd_pattern=r"assword",
        delay_factor=1,
        max_loops=20,
    ):
        """"""

        delay_factor = self.select_delay_factor(delay_factor)
        password_change_prompt = re.escape("Change now? [Y/N]")
        combined_pattern = r"({}|{}|{})".format(
            pri_prompt_terminator, alt_prompt_terminator, password_change_prompt
        )

        output = ""
        return_msg = ""
        i = 1
        while i <= max_loops:
            try:
                # Search for username pattern / send username
                output = self.read_until_pattern(pattern=username_pattern)
                return_msg += output

                self.write_channel(self.username + self.TELNET_RETURN)

                # Search for password pattern, / send password
                output = self.read_until_pattern(pattern=pwd_pattern)
                return_msg += output

                self.write_channel(self.password + self.TELNET_RETURN)

                # Search for router prompt, OR password_change prompt
                output = self.read_until_pattern(pattern=combined_pattern)
                return_msg += output

                if re.search(password_change_prompt, output):
                    self.write_channel("N" + self.TELNET_RETURN)
                    output = self.read_until_pattern(pattern=combined_pattern)
                    return_msg += output

                return return_msg
            except EOFError:
                self.remote_conn.close()
                msg = "Login failed: {}".format(self.host)
                raise NetMikoAuthenticationException(msg)

        # Last try to see if we already logged in
        self.write_channel(self.TELNET_RETURN)
        time.sleep(0.5 * delay_factor)
        output = self.read_channel()
        return_msg += output
        if re.search(pri_prompt_terminator, output, flags=re.M) or re.search(
            alt_prompt_terminator, output, flags=re.M
        ):
            return return_msg

        self.remote_conn.close()
        msg = "Login failed: {}".format(self.host)
        raise NetMikoAuthenticationException(msg)
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')
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)
963390
def main(host, password, username):
    """"""
    client = tplink.TpLinkClient(password)
    devices = client.get_connected_devices()
    click.echo(json.dumps(devices, indent=4))
    return 0
740858
def _read(self, n, initial=False, _errnos=(errno.EAGAIN, errno.EINTR)):
        """"""
        recv = self._quick_recv
        rbuf = self._read_buffer
        try:
            while len(rbuf) < n:
                try:
                    s = recv(n - len(rbuf))
                except socket.error as exc:
                    if not initial and exc.errno in _errnos:
                        continue
                    raise
                if not s:
                    raise IOError('Socket closed')
                rbuf += s
        except:
            self._read_buffer = rbuf
            raise

        result, self._read_buffer = rbuf[:n], rbuf[n:]
        return result
233404
def open(self):
        """"""
        if not self.closed:
            return
        self.outs = self.ins = open(
            "/dev/net/tun" if LINUX else ("/dev/%s" % self.iface), "r+b",
            buffering=0
        )
        if LINUX:
            from fcntl import ioctl
            # TUNSETIFF = 0x400454ca
            # IFF_TUN = 0x0001
            # IFF_TAP = 0x0002
            # IFF_NO_PI = 0x1000
            ioctl(self.ins, 0x400454ca, struct.pack(
                "16sH", bytes_encode(self.iface),
                0x0001 if self.mode_tun else 0x1002,
            ))
        self.closed = False
732069
def read_packet(sock, timeout=None):
    
    sock.settimeout(timeout)
    dlen, data = None, None
    try:
        if os.name == 'nt':
            #  Windows implementation
            datalen = sock.recv(SZ)
            dlen, = struct.unpack("l", datalen)
            data = b''
            while len(data) < dlen:
                data += sock.recv(dlen)
        else:
            #  Linux/MacOSX implementation
            #  Thanks to eborisch:
            #  See issue 1106
            datalen = temp_fail_retry(socket.error, sock.recv,
                                      SZ, socket.MSG_WAITALL)
            if len(datalen) == SZ:
                dlen, = struct.unpack("l", datalen)
                data = temp_fail_retry(socket.error, sock.recv,
                                       dlen, socket.MSG_WAITALL)
    except socket.timeout:
        raise
    except socket.error:
        data = None
    finally:
        sock.settimeout(None)
    if data is not None:
        try:
            return pickle.loads(data)
        except Exception:
            # Catch all exceptions to avoid locking spyder
            if DEBUG_EDITOR:
                traceback.print_exc(file=STDERR)
            return