本文整理汇总了Python中netrc.netrc函数的典型用法代码示例。如果您正苦于以下问题:Python netrc函数的具体用法?Python netrc怎么用?Python netrc使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了netrc函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getuser
def getuser(self):
user = None
localeval = self.localeval
if self.config.has_option(self.getsection(), 'remoteusereval'):
user = self.getconf('remoteusereval')
if user != None:
return localeval.eval(user)
user = self.getconf('remoteuser')
if user != None:
return user
try:
netrcentry = netrc.netrc().authenticators(self.gethost())
except IOError as inst:
if inst.errno != errno.ENOENT:
raise
else:
if netrcentry:
return netrcentry[0]
try:
netrcentry = netrc.netrc('/etc/netrc').authenticators(self.gethost())
except IOError as inst:
if inst.errno not in (errno.ENOENT, errno.EACCES):
raise
else:
if netrcentry:
return netrcentry[0]
示例2: getuser
def getuser(self):
user = None
localeval = self.localeval
if self.config.has_option(self.getsection(), 'remoteusereval'):
user = self.getconf('remoteusereval')
if user != None:
return localeval.eval(user).encode('UTF-8')
if self.config.has_option(self.getsection(), 'remoteuser'):
# Assume the configuration file to be UTF-8 encoded so we must not
# encode this string again.
user = self.getconf('remoteuser')
if user != None:
return user
try:
netrcentry = netrc.netrc().authenticators(self.gethost())
except IOError as inst:
if inst.errno != errno.ENOENT:
raise
else:
if netrcentry:
return netrcentry[0]
try:
netrcentry = netrc.netrc('/etc/netrc').authenticators(self.gethost())
except IOError as inst:
if inst.errno not in (errno.ENOENT, errno.EACCES):
raise
else:
if netrcentry:
return netrcentry[0]
示例3: get_netrc_login
def get_netrc_login(path, host):
try:
if path:
nrc = netrc.netrc(path)
else:
nrc = netrc.netrc()
except netrc.NetrcParseError, e:
raise Exception("%s:%d: %s" % (e.filename, e.lineno, e.msg))
示例4: _get_netrc_from_path
def _get_netrc_from_path(cls, path):
try:
return netrc.netrc(path)
except IOError:
print >> sys.stderr, 'WARNING: Could not read netrc file %s' % path
return netrc.netrc(os.devnull)
except netrc.NetrcParseError as e:
print >> sys.stderr, ('ERROR: Cannot use netrc file %s due to a '
'parsing error: %s' % (path, e))
return netrc.netrc(os.devnull)
示例5: ftp_connection_info
def ftp_connection_info(ftp_host, netrc_file):
"""Return ftp connection info from netrc and optional host address."""
if not ftp_host:
ftp_host = netrc(netrc_file).hosts.keys()[0]
logininfo = netrc(netrc_file).authenticators(ftp_host)
connection_params = {
"ftp_user": logininfo[0],
"ftp_password": logininfo[2],
}
return ftp_host, connection_params
示例6: getpassword
def getpassword(self):
"""Return the IMAP password for this repository.
It tries to get passwords in the following order:
1. evaluate Repository 'remotepasseval'
2. read password from Repository 'remotepass'
3. read password from file specified in Repository 'remotepassfile'
4. read password from ~/.netrc
5. read password from /etc/netrc
On success we return the password.
If all strategies fail we return None."""
# 1. evaluate Repository 'remotepasseval'
passwd = self.getconf('remotepasseval', None)
if passwd != None:
return self.localeval.eval(passwd).encode('UTF-8')
# 2. read password from Repository 'remotepass'
password = self.getconf('remotepass', None)
if password != None:
# Assume the configuration file to be UTF-8 encoded so we must not
# encode this string again.
return password
# 3. read password from file specified in Repository 'remotepassfile'
passfile = self.getconf('remotepassfile', None)
if passfile != None:
fd = codecs.open(os.path.expanduser(passfile), 'r', 'UTF-8')
password = fd.readline().strip()
fd.close()
return password.encode('UTF-8')
# 4. read password from ~/.netrc
try:
netrcentry = netrc.netrc().authenticators(self.gethost())
except IOError as inst:
if inst.errno != errno.ENOENT:
raise
else:
if netrcentry:
user = self.getuser()
if user == None or user == netrcentry[0]:
return netrcentry[2]
# 5. read password from /etc/netrc
try:
netrcentry = netrc.netrc('/etc/netrc').authenticators(self.gethost())
except IOError as inst:
if inst.errno not in (errno.ENOENT, errno.EACCES):
raise
else:
if netrcentry:
user = self.getuser()
if user == None or user == netrcentry[0]:
return netrcentry[2]
# no strategy yielded a password!
return None
示例7: __init__
def __init__(self, site):
try:
x = netrc.netrc()
except IOError:
homedir = os.path.expanduser('~') + '\\Application Data\\'
x = netrc.netrc(homedir + '.netrc')
info = x.authenticators(site)
self.user = info[0]
self.passwd = info[2]
self.ftp = FTP(site)
self.ftp.login(user=self.user, passwd=self.passwd)
self.setCwd(self.webRoot)
self.local = Local()
示例8: __init__
def __init__(self, site):
try:
x = netrc.netrc()
except IOError:
homedir = os.path.expanduser('~') + '\\Application Data\\'
x = netrc.netrc(homedir + '.netrc')
info = x.authenticators(site)
if not info:
raise Exception('Authentication not found in .netrc')
self.user = info[0]
self.passwd = info[2]
self.ftp = FTP(site)
self.ftp.login(user=self.user, passwd=self.passwd) #if this fails, login info incorrect
self.setCwd(self.webRoot)
self.local = Local()
示例9: install_basic_client
def install_basic_client(uri='', user='', passwd='', use_netrc=True):
# Create special opener with support for Cookies
cj = cookielib.CookieJar()
# Create the password manager and load with the credentials using
pwMgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Get passwords from the .netrc file nless use_netrc is False
if use_netrc:
logins = netrc.netrc()
accounts = logins.hosts # a dist of hosts and tuples
for host, info in accounts.iteritems():
login, account, password = info
# log.debug('Host: %s; login: %s; account: %s; password: %s' % (host, login, account, password))
pwMgr.add_password(None, host, login, password)
if uri and user and passwd:
pwMgr.add_password(None, uri, user, passwd)
opener = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(pwMgr), urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('User-agent', pydap.lib.USER_AGENT)]
urllib2.install_opener(opener)
def new_request(url):
if url[-1] is '&': url = url[0:-1]
# log.debug('Opening %s (install_basic_client)' % url)
r = urllib2.urlopen(url)
resp = r.headers.dict
resp['status'] = str(r.code)
data = r.read()
# When an error is returned, we parse the error message from the
# server and return it in a ``ClientError`` exception.
if resp.get("content-description") == "dods_error":
m = re.search('code = (?P<code>\d+);\s*message = "(?P<msg>.*)"', data, re.DOTALL | re.MULTILINE)
msg = 'Server error %(code)s: "%(msg)s"' % m.groupdict()
raise ClientError(msg)
return resp, data
from pydap.util import http
http.request = new_request
示例10: get_credentials
def get_credentials(username=None, password=None):
try:
my_netrc = netrc.netrc()
except:
pass
else:
auth = my_netrc.authenticators(GITHUB_API_HOST)
if auth:
response = ''
while response.lower() not in ('y', 'n'):
print('Using the following GitHub credentials from '
'~/.netrc: {0}/{1}'.format(auth[0], '*' * 8))
response = input(
'Use these credentials (if not you will be prompted '
'for new credentials)? [Y/n] ')
if response.lower() == 'y':
username = auth[0]
password = auth[2]
if not (username or password):
print("Enter your GitHub username and password so that API "
"requests aren't as severely rate-limited...")
username = raw_input('Username: ')
password = getpass.getpass('Password: ')
elif not password:
print("Enter your GitHub password so that API "
"requests aren't as severely rate-limited...")
password = getpass.getpass('Password: ')
return username, password
示例11: _login
def _login(self):
login, _, password = netrc().hosts['instagram']
credentials = {
'username': login,
'password': password
}
main_page = self._session.get('https://www.instagram.com/')
anti_rate_limit_sleep()
csrftoken = main_page.cookies['csrftoken']
self._update_headers(csrftoken)
login_result = self._session.post(
'https://www.instagram.com/accounts/login/ajax/',
data=credentials)
anti_rate_limit_sleep()
main_page_again = self._session.get('https://www.instagram.com/')
spit(main_page_again.text, 'main-after-login.html')
anti_rate_limit_sleep()
if not InstaAPI.SHARED_DATA_SUBSTRING in main_page_again.content:
_log.error('No line with sharedData in main page response (login)')
_log.error(main_page_again.content)
return False
_log.debug('Logged in')
save_cookies(self._session, 'cookies.json')
self._query_hash = self._find_query_hash(main_page_again.text)
return True
示例12: on_authentication_required
def on_authentication_required(self, reply, authenticator):
"""Called when a website needs authentication."""
user, password = None, None
if not hasattr(reply, "netrc_used") and 'HOME' in os.environ:
# We'll get an OSError by netrc if 'HOME' isn't available in
# os.environ. We don't want to log that, so we prevent it
# altogether.
reply.netrc_used = True
try:
net = netrc.netrc()
authenticators = net.authenticators(reply.url().host())
if authenticators is not None:
(user, _account, password) = authenticators
except FileNotFoundError:
log.misc.debug("No .netrc file found")
except OSError:
log.misc.exception("Unable to read the netrc file")
except netrc.NetrcParseError:
log.misc.exception("Error when parsing the netrc file")
if user is None:
# netrc check failed
answer = self._ask("Username ({}):".format(authenticator.realm()),
mode=usertypes.PromptMode.user_pwd,
owner=reply)
if answer is not None:
user, password = answer.user, answer.password
if user is not None:
authenticator.setUser(user)
authenticator.setPassword(password)
示例13: _parse_opts
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("--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 = []
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:
raise netrc.NetrcParseError("No authenticators for %s" % host)
opts.threshold /= 100
return opts
示例14: main
def main():
h5r_netrc = netrc.netrc()
(username, account, password) = h5r_netrc.authenticators("html5rocks.com")
g = Github(password)
repo = g.get_repo(repository)
open_issues = repo.get_issues(state="open")
closed_issues = repo.get_issues(state="closed")
issues = []
[issues.append(i) for i in open_issues]
[issues.append(i) for i in closed_issues]
today = datetime.today()
completed_articles, late_articles, due_articles = ParseIssues(issues)
print "HTML5 Rocks Quarter Report for %s" % today.date()
print "=========================================\n"
print "Articles due this quater"
print "------------------------\n"
if len(due_articles) == 0:
print "There are no articles due this quarter, either all is good, or something messed up!\n"
else:
print "|Author|Article|Delivery date|Tech Writer|State|"
print "|------|-------|-------------|-----------|-----|"
for article in due_articles:
print "|%s|[%s](%s)|%s|%s|%s" % ((article.assignee or article.user).name, article.title, article.html_url, article.due_on.date(), article.tech_writer, article.state)
示例15: _get_login_info
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('parsing .netrc: %s' % compat_str(err))
return (username, password)