def _get_login_info(self): """ Get the 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(u'parsing .netrc: %s' % compat_str(err)) return (username, password)
def _real_initialize(self): if self._downloader is None: return 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), err: self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err)) return
def connection(token_type): ''' Initialize connection with Spotinst API ''' try: account = netrc.netrc().authenticators(token_type)[0] token = netrc.netrc().authenticators(token_type)[2] except: netrc.NetrcParseError( "No authenticators for %s" %token_type) print ("Can't find .netrc file. Exiting") sys.exit(1) spotinst_client = spotinst_sdk.SpotinstClient(auth_token=token, account_id=account) return spotinst_client
def get_netrc_login_info(netrc_machine=None): username = None password = None 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 {}'.format(netrc_machine)) except (IOError, netrc.NetrcParseError) as err: print('error parsing .netrc: {}'.format(err)) return username, password
def _real_initialize(self): if self._downloader is None: return useremail = 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: useremail = 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: useremail = 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(u'parsing .netrc: %s' % compat_str(err)) return if useremail is None: return # Log in login_form = {'email': useremail, 'pass': password, 'login': '******'} request = compat_urllib_request.Request( self._LOGIN_URL, compat_urllib_parse.urlencode(login_form)) try: self.report_login() login_results = compat_urllib_request.urlopen(request).read() if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None: self._downloader.report_warning( u'unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.' ) return except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err: self._downloader.report_warning(u'unable to log in: %s' % compat_str(err)) return
def _netrc_open(uri, filename=None): ''' open uri using netrc credentials. :param uri: uri to open :param filename: optional, path to non-default netrc config file :returns: file-like object from opening a socket to uri, or None :raises IOError: if opening .netrc file fails (unless file not found) ''' if not uri: return None parsed_uri = urlparse(uri) machine = parsed_uri.netloc if not machine: return None opener = None try: info = netrc.netrc(filename).authenticators(machine) if info is not None: (username, _, password) = info if username and password: pass_man = HTTPPasswordMgrWithDefaultRealm() pass_man.add_password(None, machine, username, password) authhandler = HTTPBasicAuthHandler(pass_man) opener = build_opener(authhandler) return opener.open(uri) else: # caught below, like other netrc parse errors raise netrc.NetrcParseError('No authenticators for "%s"' % machine) except IOError as ioe: if ioe.errno != 2: # if = 2, User probably has no .netrc, this is not an error raise except netrc.NetrcParseError as neterr: logger = logging.getLogger('vcstools') logger.warn('WARNING: parsing .netrc: %s' % str(neterr)) # we could install_opener() here, but prefer to keep # default opening clean. Client can do that, though. return None
def main(): try: # Test if input is a valid URL or file url_mo = valid_url(cmdl_opts.input) if not url_mo: open(cmdl_opts.input) account_username = cmdl_opts.username account_password = cmdl_opts.password if cmdl_opts.netrc: if cmdl_opts.username or cmdl_opts.password: output("Ignorning input credentials in favor of .netrc (-n)\n", logging.WARNING) account_credentials = netrc.netrc().authenticators(HOST) if account_credentials: account_username = account_credentials[0] account_password = account_credentials[2] else: raise netrc.NetrcParseError( "No authenticator available for {}".format(HOST)) if not account_username: account_username = input("Username: "******"Password: "******"{0}: {1}\n".format( type(error).__name__, str(error))) traceback.print_exc()
def _parse_opts(args): parser = argparse.ArgumentParser( description= "Compare two Graphite clusters for a given list of queries.", epilog= "Through this module, a \"query\" is \"the name of a query\", a string." ) # authentication authentication = parser.add_argument_group("authentication") authentication.add_argument( "--netrc-file", metavar="FILENAME", dest="netrc_filename", action="store", help="a netrc file (default: $HOME/$USER/.netrc)", default="") # clusters parameters comparison_params = parser.add_argument_group("comparison parameters") comparison_params.add_argument("--hosts", metavar="HOST", dest="hosts", action="store", nargs=2, help="hosts to compare", required=True) comparison_params.add_argument("--prefixes", metavar="PREFIX", dest="prefixes", action="store", nargs=2, help="prefix for each host.", required=False, default=["", ""]) comparison_params.add_argument( "--input-file", metavar="FILENAME", dest="input_filename", action="store", help="text file containing one query per line", required=True) comparison_params.add_argument( "--from", metavar="FROM_PARAM", dest="from_param", action="store", default="-24hours", help="from param for Graphite API (default: %(default)s)") comparison_params.add_argument( "--until", metavar="UNTIL_PARAM", dest="until_param", action="store", default="-2minutes", help="until param for Graphite API (default: %(default)s)") comparison_params.add_argument( "--timeout", metavar="SECONDS", dest="timeout_s", action="store", type=float, help="timeout in seconds used to fetch queries (default: %(default)ss)", default=5) comparison_params.add_argument( "--threshold", metavar="PERCENT", action="store", type=float, default=1, help= "percent threshold to evaluate equality between two values (default: %(default)s%%)" ) # outputs parameters outputs_params = parser.add_argument_group("outputs parameters") outputs_params.add_argument( "--output-file", metavar="FILENAME", dest="output_filename", action="store", help="file containing outputs (default: stdout)", default="") outputs_params.add_argument( "-v", "--verbosity", action="count", default=0, help="increases verbosity, can be passed multiple times") outputs_params.add_argument( "--show-max", metavar="N_LINES", dest="show_max", type=int, default=5, help= "truncate the number of shown dissymmetry in outputs (default: %(default)s)" ) # TODO (t.chataigner) enable several kind of outputs : txt, csv, html... opts = parser.parse_args(args) # compute authentication keys from netrc file opts.auth_keys = [None, None] for host in opts.hosts: auth = netrc.netrc().authenticators(host) if auth is not None: username = auth[0] password = auth[2] opts.auth_keys.append( base64.encodestring(username + ":" + password).replace( "\n", "")) else: logging.info( netrc.NetrcParseError("No authenticators for %s" % host)) opts.threshold /= 100 return opts
def retrieve_from_netrc(machine): login = netrc.netrc().authenticators(machine) if not login: raise netrc.NetrcParseError('No authenticators for %s' % machine) return login
# Copyright (c) 2015, Nicolas Meier # ####################################################################### import sys import requests import collections import math import netrc import pymysql import re import urllib import urllib.parse import pylast if len(sys.argv) != 2: raise netrc.NetrcParseError('Missing Last.fm username.') # Call the script with your Last.fm username. user = sys.argv[1] def retrieve_from_netrc(machine): login = netrc.netrc().authenticators(machine) if not login: raise netrc.NetrcParseError('No authenticators for %s' % machine) return login # Get the Last.fm API key api_key = '97a866cdf5a8d69617c37d1bb150da4f'