本文整理汇总了Python中netrc.netrc函数的典型用法代码示例。如果您正苦于以下问题:Python netrc函数的具体用法?Python netrc怎么用?Python netrc使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了netrc函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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]
开发者ID:Stebalien,项目名称:offlineimap,代码行数:30,代码来源:IMAP.py
示例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]
开发者ID:ordnungswidrig,项目名称:offlineimap,代码行数:33,代码来源:IMAP.py
示例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))
开发者ID:lbovet,项目名称:misc-utils,代码行数:8,代码来源:greader.py
示例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)
开发者ID:sharpglasses,项目名称:depot_tools,代码行数:10,代码来源:gerrit_util.py
示例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
开发者ID:bittirousku,项目名称:hepcrawl,代码行数:10,代码来源:utils.py
示例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
开发者ID:ordnungswidrig,项目名称:offlineimap,代码行数:55,代码来源:IMAP.py
示例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()
开发者ID:skilldrick,项目名称:dilbert,代码行数:13,代码来源:upload.py
示例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()
开发者ID:skilldrick,项目名称:upload,代码行数:15,代码来源:upload.py
示例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
开发者ID:ESMG,项目名称:pyroms,代码行数:34,代码来源:get_MERRA_Pair_from_nasa_opendap_3hours.py
示例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
开发者ID:bsipocz,项目名称:astropy-tools,代码行数:30,代码来源:issue2pr.py
示例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
开发者ID:balta2ar,项目名称:insave,代码行数:31,代码来源:insave.py
示例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)
开发者ID:Dietr1ch,项目名称:qutebrowser,代码行数:30,代码来源:networkmanager.py
示例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
开发者ID:natbraun,项目名称:biggraphite,代码行数:60,代码来源:clusters_diff.py
示例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)
开发者ID:Adam-Michal-Prague,项目名称:www.html5rocks.com,代码行数:31,代码来源:overdue-report.py
示例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)
开发者ID:larrywhy,项目名称:youtube-dl,代码行数:29,代码来源:common.py
示例16: netrc_from_env
def netrc_from_env():
netrc_obj = None
netrc_path = os.environ.get('NETRC')
try:
if netrc_path is not None:
netrc_path = Path(netrc_path)
else:
home_dir = Path.home()
if os.name == 'nt': # pragma: no cover
netrc_path = home_dir.joinpath('_netrc')
else:
netrc_path = home_dir.joinpath('.netrc')
if netrc_path and netrc_path.is_file():
try:
netrc_obj = netrc.netrc(str(netrc_path))
except (netrc.NetrcParseError, OSError) as e:
client_logger.warning(".netrc file parses fail: %s", e)
if netrc_obj is None:
client_logger.warning("could't find .netrc file")
except RuntimeError as e: # pragma: no cover
""" handle error raised by pathlib """
client_logger.warning("could't find .netrc file: %s", e)
return netrc_obj
开发者ID:youpengly,项目名称:aiohttp,代码行数:25,代码来源:helpers.py
示例17: set_parser
def set_parser(self, args=None):
if args is None:
args = self.parser.parse_args()
self.args = args
# セッションが保存されていた場合、それを使う
if path.exists(cookie_path):
self.load_cookies()
# ログインできていたらリターン
if self.is_logged_in():
return
mail = args.mail
password = args.passwd
# ユーザー名とパスワードをnetrcから取得
if mail is None or password is None:
try:
auth = netrc.netrc()
mail, _, password = auth.authenticators("nicovideo")
except OSError as e:
print(e)
raise LoginFailedException("ログインに失敗しました")
# ログインしてセッションを取得
self.mail = mail
self.password = password
self.web_driver = args.web_driver
self.login()
开发者ID:archiba,项目名称:pyniconico,代码行数:26,代码来源:nicowalker.py
示例18: delete_heroku_server
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
)
))
开发者ID:ahiroto,项目名称:ParlAI,代码行数:27,代码来源:server_utils.py
示例19: 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"):
reply.netrc_used = True
try:
net = netrc.netrc()
authenticators = net.authenticators(reply.url().host())
if authenticators is not None:
# pylint: disable=unpacking-non-sequence
(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)
开发者ID:vyp,项目名称:qutebrowser,代码行数:29,代码来源:networkmanager.py
示例20: get_netrc_auth
def get_netrc_auth(url):
try:
from netrc import netrc, NetrcParseError
netrc_path = None
for f in NETRC_FILES:
try:
loc = os.path.expanduser('~/{0}'.format(f))
except KeyError:
return
if os.path.exists(loc):
netrc_path = loc
break
if netrc_path is None:
return
ri = urlparse(url)
host = ri.netloc.split(':')[0]
try:
_netrc = netrc(netrc_path).authenticators(host)
if _netrc:
login_i = 0 if _netrc[0] else 1
return (_netrc[login_i], _netrc[2])
except (NetrcParseError, IOError):
pass
except (ImportError, AttributeError):
pass
开发者ID:connoryang,项目名称:dec-eve-serenity,代码行数:28,代码来源:utils.py
注:本文中的netrc.netrc函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论