我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用netrc.netrc()。
def _get_netrc_login_info(self, netrc_machine=None): username = None password = None netrc_machine = netrc_machine or self._NETRC_MACHINE if self._downloader.params.get('usenetrc', False): try: info = netrc.netrc().authenticators(netrc_machine) if info is not None: username = info[0] password = info[2] else: raise netrc.NetrcParseError( 'No authenticators for %s' % netrc_machine) except (IOError, netrc.NetrcParseError) as err: self._downloader.report_warning( 'parsing .netrc: %s' % error_to_compat_str(err)) return username, password
def render_to_file_and_deploy(self): username, acc, password = \ netrc.netrc().authenticators(self._device.name) device_data = { 'device_type': 'cisco_ios', 'ip': self._device.name, 'username': username, 'password': password, } f = NamedTemporaryFile(delete=False) print('Stored temporary config at {}'.format(f.name)) f.write(self._device.rendered_config) f.flush() net_connect = ConnectHandler(**device_data) output = net_connect.send_config_from_file(f.name) print(output) print('Config uploaded!') f.close() print('Done.')
def _get_login_info(self, username_option='username', password_option='password', netrc_machine=None): """ Get the login info as (username, password) First look for the manually specified credentials using username_option and password_option as keys in params dictionary. If no such credentials available look in the netrc file using the netrc_machine or _NETRC_MACHINE value. If there's no info available, return (None, None) """ if self._downloader is None: return (None, None) downloader_params = self._downloader.params # Attempt to use provided username and password or .netrc data if downloader_params.get(username_option) is not None: username = downloader_params[username_option] password = downloader_params[password_option] else: username, password = self._get_netrc_login_info(netrc_machine) return username, password
def _init_github_account(self): try: info = netrc.netrc().authenticators(self._NETRC_MACHINE) if info is not None: self._username = info[0] self._password = info[2] compat_print('Using GitHub credentials found in .netrc...') return else: compat_print('No GitHub credentials found in .netrc') except (IOError, netrc.NetrcParseError): compat_print('Unable to parse .netrc') self._username = compat_input( 'Type your GitHub username or email address and press [Return]: ') self._password = compat_getpass( 'Type your GitHub password and press [Return]: ')
def test_security(self): # This test is incomplete since we are normally not run as root and # therefore can't test the file ownership being wrong. d = test_support.TESTFN os.mkdir(d) self.addCleanup(test_support.rmtree, d) fn = os.path.join(d, '.netrc') with open(fn, 'wt') as f: f.write("""\ machine foo.domain.com login bar password pass default login foo password pass """) with test_support.EnvironmentVarGuard() as environ: environ.set('HOME', d) os.chmod(fn, 0600) nrc = netrc.netrc() self.assertEqual(nrc.hosts['foo.domain.com'], ('bar', None, 'pass')) os.chmod(fn, 0o622) self.assertRaises(netrc.NetrcParseError, netrc.netrc)
def test_security(self): # This test is incomplete since we are normally not run as root and # therefore can't test the file ownership being wrong. d = support.TESTFN os.mkdir(d) self.addCleanup(support.rmtree, d) fn = os.path.join(d, '.netrc') with open(fn, 'wt') as f: f.write("""\ machine foo.domain.com login bar password pass default login foo password pass """) with support.EnvironmentVarGuard() as environ: environ.set('HOME', d) os.chmod(fn, 0o600) nrc = netrc.netrc() self.assertEqual(nrc.hosts['foo.domain.com'], ('bar', None, 'pass')) os.chmod(fn, 0o622) self.assertRaises(netrc.NetrcParseError, netrc.netrc)
def raise_login_required(msg='This video is only available for registered users'): raise ExtractorError( '%s. Use --username and --password or --netrc to provide account credentials.' % msg, expected=True)
def _get_login_info(self): """ Get the login info as (username, password) It will look in the netrc file using the _NETRC_MACHINE value If there's no info available, return (None, None) """ if self._downloader is None: return (None, None) username = None password = None downloader_params = self._downloader.params # Attempt to use provided username and password or .netrc data if downloader_params.get('username', None) is not None: username = downloader_params['username'] password = downloader_params['password'] elif downloader_params.get('usenetrc', False): try: info = netrc.netrc().authenticators(self._NETRC_MACHINE) if info is not None: username = info[0] password = info[2] else: raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE) except (IOError, netrc.NetrcParseError) as err: self._downloader.report_warning('parsing .netrc: %s' % error_to_compat_str(err)) return (username, password)
def delete_heroku_server(task_name): heroku_directory_name = \ glob.glob(os.path.join(parent_dir, 'heroku-cli-*'))[0] heroku_directory_path = os.path.join(parent_dir, heroku_directory_name) heroku_executable_path = \ os.path.join(heroku_directory_path, 'bin', 'heroku') heroku_user_identifier = ( netrc.netrc(os.path.join(os.path.expanduser("~"), '.netrc')) .hosts['api.heroku.com'][0] ) heroku_app_name = ('{}-{}-{}'.format( user_name, task_name, hashlib.md5(heroku_user_identifier.encode('utf-8')).hexdigest() ))[:30] while heroku_app_name[-1] == '-': heroku_app_name = heroku_app_name[:-1] print("Heroku: Deleting server: {}".format(heroku_app_name)) subprocess.check_output(shlex.split( '{} destroy {} --confirm {}'.format( heroku_executable_path, heroku_app_name, heroku_app_name ) ))
def netrc_exists(): try: my_netrc = netrc.netrc() except FileNotFoundError: return False else: return my_netrc.authenticators('api.github.com') is not None
def get_installation_token(installation): """ Get access token for installation """ now = datetime.datetime.now().timestamp() if installation_token_expiry[installation] is None or now + 60 > installation_token_expiry[installation]: # FIXME: if .netrc file is present, Authorization header will get # overwritten, so need to figure out how to ignore that file. if netrc_exists(): raise Exception("Authentication does not work properly if a ~/.netrc " "file exists. Rename that file temporarily and try again.") headers = {} headers['Authorization'] = 'Bearer {0}'.format(get_json_web_token()) headers['Accept'] = 'application/vnd.github.machine-man-preview+json' url = 'https://api.github.com/installations/{0}/access_tokens'.format(installation) req = requests.post(url, headers=headers) resp = req.json() if not req.ok: if 'message' in resp: raise Exception(resp['message']) else: raise Exception("An error occurred when requesting token") installation_token[installation] = resp['token'] installation_token_expiry[installation] = dateutil.parser.parse(resp['expires_at']).timestamp() return installation_token[installation]
def get_netrc_auth(url): """Returns the Requests tuple auth for a given url from netrc.""" try: locations = (os.path.expanduser('~/{0}'.format(f)) for f in NETRC_FILES) netrc_path = None for loc in locations: if os.path.exists(loc) and not netrc_path: netrc_path = loc # Abort early if there isn't one. if netrc_path is None: return netrc_path ri = urlparse(url) # Strip port numbers from netloc host = ri.netloc.split(':')[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth pass # AppEngine hackiness. except (ImportError, AttributeError): pass
def get_netrc_auth(url): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError locations = (os.path.expanduser('~/{0}'.format(f)) for f in NETRC_FILES) netrc_path = None for loc in locations: if os.path.exists(loc) and not netrc_path: netrc_path = loc # Abort early if there isn't one. if netrc_path is None: return netrc_path ri = urlparse(url) # Strip port numbers from netloc host = ri.netloc.split(':')[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth pass # AppEngine hackiness. except (ImportError, AttributeError): pass
def login(self, user=None, password=None, usenetrc=True): if self.authenticated: raise ValueError("Already logged in.") if not user and not usenetrc: raise ValueError( "At least one of `user` and `usenetrc` must be specified") # If no login/password was specified but netrc was requested, # try to get them from ~/.netrc # Presume that if .netrc has an entry, NNRP authentication is required. try: if usenetrc and not user: import netrc credentials = netrc.netrc() auth = credentials.authenticators(self.host) if auth: user = auth[0] password = auth[2] except IOError: pass # Perform NNTP authentication if needed. if not user: return resp = self._shortcmd('authinfo user ' + user) if resp.startswith('381'): if not password: raise NNTPReplyError(resp) else: resp = self._shortcmd('authinfo pass ' + password) if not resp.startswith('281'): raise NNTPPermanentError(resp) # Capabilities might have changed after login self._caps = None self.getcapabilities() # Attempt to send mode reader if it was requested after login. # Only do so if we're not in reader mode already. if self.readermode_afterauth and 'READER' not in self._caps: self._setreadermode() # Capabilities might have changed after MODE READER self._caps = None self.getcapabilities()
def __init__(self, host, port=NNTP_PORT, user=None, password=None, readermode=None, usenetrc=False, timeout=_GLOBAL_DEFAULT_TIMEOUT): """Initialize an instance. Arguments: - host: hostname to connect to - port: port to connect to (default the standard NNTP port) - user: username to authenticate with - password: password to use with username - readermode: if true, send 'mode reader' command after connecting. - usenetrc: allow loading username and password from ~/.netrc file if not specified explicitly - timeout: timeout (in seconds) used for socket connections readermode is sometimes necessary if you are connecting to an NNTP server on the local machine and intend to call reader-specific commands, such as `group'. If you get unexpected NNTPPermanentErrors, you might need to set readermode. """ self.host = host self.port = port self.sock = socket.create_connection((host, port), timeout) file = self.sock.makefile("rwb") _NNTPBase.__init__(self, file, host, readermode, timeout) if user or usenetrc: self.login(user, password, usenetrc)
def make_nrc(self, test_data): test_data = textwrap.dedent(test_data) mode = 'w' if sys.platform != 'cygwin': mode += 't' with open(temp_filename, mode) as fp: fp.write(test_data) return netrc.netrc(temp_filename)
def get_login_password(site_name="github.com", netrc_file="~/.netrc"): """Read a .netrc file and return login/password for LWN.""" n = netrc.netrc(os.path.expanduser(netrc_file)) return n.hosts[site_name][0], n.hosts[site_name][2]
def make_nrc(self, test_data): test_data = textwrap.dedent(test_data) mode = 'w' if sys.platform != 'cygwin': mode += 't' with open(temp_filename, mode) as fp: fp.write(test_data) self.addCleanup(os.unlink, temp_filename) return netrc.netrc(temp_filename)
def _get_login_info(self): """ Get the login info as (username, password) It will look in the netrc file using the _NETRC_MACHINE value If there's no info available, return (None, None) """ if self._downloader is None: return (None, None) username = None password = None downloader_params = self._downloader.params # Attempt to use provided username and password or .netrc data if downloader_params.get('username') is not None: username = downloader_params['username'] password = downloader_params['password'] elif downloader_params.get('usenetrc', False): try: info = netrc.netrc().authenticators(self._NETRC_MACHINE) if info is not None: username = info[0] password = info[2] else: raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE) except (IOError, netrc.NetrcParseError) as err: self._downloader.report_warning('parsing .netrc: %s' % error_to_compat_str(err)) return (username, password)
def get_netrc_auth(url, raise_errors=False): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError netrc_path = None for f in NETRC_FILES: try: loc = os.path.expanduser('~/{0}'.format(f)) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See http://bugs.python.org/issue20164 & # https://github.com/kennethreitz/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc. This weird `if...encode`` dance is # used for Python 3.2, which doesn't support unicode literals. splitstr = b':' if isinstance(url, str): splitstr = splitstr.decode('ascii') host = ri.netloc.split(splitstr)[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth unless explicitly asked to raise errors. if raise_errors: raise # AppEngine hackiness. except (ImportError, AttributeError): pass
def get_netrc_auth(url, raise_errors=False): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError netrc_path = None for f in NETRC_FILES: try: loc = os.path.expanduser('~/{0}'.format(f)) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See http://bugs.python.org/issue20164 & # https://github.com/requests/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc. This weird `if...encode`` dance is # used for Python 3.2, which doesn't support unicode literals. splitstr = b':' if isinstance(url, str): splitstr = splitstr.decode('ascii') host = ri.netloc.split(splitstr)[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth unless explicitly asked to raise errors. if raise_errors: raise # AppEngine hackiness. except (ImportError, AttributeError): pass
def get_netrc_auth(url): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError netrc_path = None for f in NETRC_FILES: try: loc = os.path.expanduser('~/{0}'.format(f)) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See http://bugs.python.org/issue20164 & # https://github.com/kennethreitz/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc host = ri.netloc.split(':')[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth pass # AppEngine hackiness. except (ImportError, AttributeError): pass