我试图找到如何在python中使用urllib2进行基本身份验证以获取问题KEY JIRA REST API描述了URI的可用性

感谢sugestions,我会尝试它,同时,我只是想用自己的努力更新这个:这是我试过的示例python代码:

import urllib2, sys, re, base64
from urlparse import urlparse
theurl = 'http://my.rest-server.com:8080/rest/api/latest/AA-120'            # if you want to run this example you'll need to supply a protected page with y
our username and password
username = 'username'
password = 'password'            # a very bad password

req = urllib2.Request(theurl)
print req
try:
    handle = urllib2.urlopen(req)
    print handle
except IOError, e:                  # here we are assuming we fail
    pass
else:                               # If we don't fail then the page isn't protected
    print "This page isn't protected by authentication."
    sys.exit(1)
if not hasattr(e, 'code') or e.code != 401:                 # we got an error - but not a 401 error
    print "This page isn't protected by authentication."
    print 'But we failed for another reason.'
    sys.exit(1)

authline = e.headers.get('www-authenticate', '')                # this gets the www-authenticat line from the headers - which has the authentication
 scheme and realm in it
if not authline:
    print 'A 401 error without an authentication response header - very weird.'
    sys.exit(1)
authobj = re.compile(r'''(?:\s*www-authenticate\s*:)?\s*(\w*)\s+realm=['"](\w+)['"]''', re.IGNORECASE)          # this regular expression is used to
 extract scheme and realm
matchobj = authobj.match(authline)
if not matchobj:                                        # if the authline isn't matched by the regular expression then something is wrong
    print 'The authentication line is badly formed.'
    sys.exit(1)
scheme = matchobj.group(1)
print scheme
realm = matchobj.group(2)
print realm
if scheme.lower() != 'basic':
    print 'This example only works with BASIC authentication.'
    sys.exit(1)

base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
authheader =  "Basic %s" % base64string
req.add_header("Authorization", authheader)
try:
    handle = urllib2.urlopen(req)
except IOError, e:                  # here we shouldn't fail if the username/password is right
    print "It looks like the username or password is wrong."
    sys.exit(1)
thepage = handle.read()
server = urlparse(theurl)[1].lower()            # server names are case insensitive, so we will convert to lower case
test = server.find(':')
if test != -1: server = server[:test]           # remove the :port information if present, we're working on the principle that realm names per serve
r are likely to be unique...

passdict = {(server, realm) : authheader }      # now if we get another 401 we can test for an entry in passdict before having to ask the user for a
 username/password

print 'Done successfully - information now stored in passdict.'
print 'The webpage is stored in thepage.'

---我得到结果:此页面不受身份验证保护。 但我们失败了另一个原因。

而页面受身份验证保护

我尝试安装请求,但收到错误:

sudo easy_install requests
Searching for requests
Reading http://pypi.python.org/simple/requests/

Reading https://github.com/kennethreitz/requests
Reading http://python-requests.org
Best match: requests 0.9.1
Downloading http://pypi.python.org/packages/source/r/requests/requests-0.9.1.tar.gz#md5=8ed4667edb5d57945b74a9137adbb8bd
Processing requests-0.9.1.tar.gz
Running requests-0.9.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-lTQu8K/requests-0.9.1/egg-dist-tmp-M2yQCt
Traceback (most recent call last):
  File "/usr/bin/easy_install", line 7, in ?
    sys.exit(
  File "/usr/lib/python2.4/site-packages/setuptools-0.6c12dev_r88846-py2.4.egg/setuptools/command/easy_install.py", line 1712, in main
    with_ei_usage(lambda:
  File "/usr/lib/python2.4/site-packages/setuptools-0.6c12dev_r88846-py2.4.egg/setuptools/command/easy_install.py", line 1700, in with_ei_usage
    return f()
  File "/usr/lib/python2.4/site-packages/setuptools-0.6c12dev_r88846-py2.4.egg/setuptools/command/easy_install.py", line 1716, in <lambda>
    distclass=DistributionWithoutHelpCommands, **kw
  File "/usr/lib64/python2.4/distutils/core.py", line 149, in setup
    dist.run_commands()
  File "/usr/lib64/python2.4/distutils/dist.py", line 946, in run_commands
    self.run_command(cmd)
  File "/usr/lib64/python2.4/distutils/dist.py", line 966, in run_command
    cmd_obj.run()
  File "/usr/lib/python2.4/site-packages/setuptools-0.6c12dev_r88846-py2.4.egg/setuptools/command/easy_install.py", line 211, in run
    self.easy_install(spec, not self.no_deps)
  File "/usr/lib/python2.4/site-packages/setuptools-0.6c12dev_r88846-py2.4.egg/setuptools/command/easy_install.py", line 446, in easy_install
    return self.install_item(spec, dist.location, tmpdir, deps)
  File "/usr/lib/python2.4/site-packages/setuptools-0.6c12dev_r88846-py2.4.egg/setuptools/command/easy_install.py", line 476, in install_item
    dists = self.install_eggs(spec, download, tmpdir)
  File "/usr/lib/python2.4/site-packages/setuptools-0.6c12dev_r88846-py2.4.egg/setuptools/command/easy_install.py", line 655, in install_eggs
    return self.build_and_install(setup_script, setup_base)
  File "/usr/lib/python2.4/site-packages/setuptools-0.6c12dev_r88846-py2.4.egg/setuptools/command/easy_install.py", line 930, in build_and_install
    self.run_setup(setup_script, setup_base, args)
  File "/usr/lib/python2.4/site-packages/setuptools-0.6c12dev_r88846-py2.4.egg/setuptools/command/easy_install.py", line 919, in run_setup
    run_setup(setup_script, args)
  File "/usr/lib/python2.4/site-packages/setuptools-0.6c12dev_r88846-py2.4.egg/setuptools/sandbox.py", line 61, in run_setup
    DirectorySandbox(setup_dir).run(
  File "/usr/lib/python2.4/site-packages/setuptools-0.6c12dev_r88846-py2.4.egg/setuptools/sandbox.py", line 105, in run
    return func()
  File "/usr/lib/python2.4/site-packages/setuptools-0.6c12dev_r88846-py2.4.egg/setuptools/sandbox.py", line 64, in <lambda>
    {'__file__':setup_script, '__name__':'__main__'}
  File "setup.py", line 6, in ?
  File "/tmp/easy_install-lTQu8K/requests-0.9.1/requests/__init__.py", line 26
    from . import utils
         ^
SyntaxError: invalid syntax

===============>>#1 票数:6

我建议考虑使用非常出色的requests库,它提供了一个很好的抽象,使urllib2更容易使用。

有了requests您可以简单地执行:

r = requests.get('https://api.github.com', auth=('user', 'pass'))

它支持进行REST调用所需的所有请求方法(POST,PUT,DELETE等等)。

你可以在这里找到更多:

http://pypi.python.org/pypi/requests


如果你绝对必须使用普通的旧urllib2,这里有一个如何完成它的例子:

import urllib2

theurl = 'http://www.someserver.com/toplevelurl/somepage.htm'
username = 'johnny'
password = 'XXXXXX'

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, theurl, username, password)
# because we have put None at the start it will always
# use this username/password combination for  urls
# for which `theurl` is a super-url

authhandler = urllib2.HTTPBasicAuthHandler(passman)

opener = urllib2.build_opener(authhandler)

urllib2.install_opener(opener)
# All calls to urllib2.urlopen will now use our handler
# Make sure not to include the protocol in with the URL, or
# HTTPPasswordMgrWithDefaultRealm will be very confused.
# You must (of course) use it when fetching the page though.

pagehandle = urllib2.urlopen(theurl)
# authentication is now handled automatically for us

更多信息可以在这里找到: http//www.voidspace.org.uk/python/articles/authentication.shtml

===============>>#2 票数:4 已采纳

好笑,我昨天正在为JIRA Python CLI工作 我采用了使用REST API的方法来获取身份验证cookie和自定义开启工具。 下面的示例显示使用opener将数据发布到页面以添加组件,但您可以将其替换为对不同REST调用的正确URL的调用。

    """
Demonstration of using Python for a RESTful call to JIRA

Matt Doar
CustomWare
"""

import urllib
import urllib2
import cookielib

jira_serverurl = "http://jira.example.com:8080"
creds = { "username" : "admin", "password" : "admin" }
authurl = jira_serverurl + "/rest/auth/latest/session"

# Get the authentication cookie using the REST API
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
req = urllib2.Request(authurl)
req.add_data('{ "username" : "admin", "password" : "admin" }')
req.add_header("Content-type", "application/json")
req.add_header("Accept", "application/json")
fp = opener.open(req)
fp.close()

add_component_url = jira_serverurl + "/secure/project/AddComponent.jspa?pid=10020&name=ABC4"
print "Using %s" % (add_component_url)

# Have to add data to make urllib2 send a POST
values = {}
data = urllib.urlencode(values)

# Have to tell JIRA to not use a form token
headers = {'X-Atlassian-Token': 'no-check'}

request = urllib2.Request(add_component_url, data, headers=headers)
fp = opener.open(request)

print fp.read()

===============>>#3 票数:2

我使用请求模块取得了更大的成功。

import requests

jira_session = requests.session()

try:
    jira_session.post('https://server', auth=(user, password), verify=False)
except:
    print('Unable to connect or authenticate with JIRA server.')

url = 'https://server/rest/api/2/search?jql=project="ABCXYZ"&maxResults=100'
results = jira_session.get(url)
project_data = results.json()

===============>>#4 票数:1

我在访问Jira REST时遇到了同样的问题。 这对我有用:

class JiraOpenerWrapper(object):
  # Class to wrap urllib2 OpenerDirector to add authenication headers.
  # this is needed fro Jira - see comment below.
  def __init__(self, opener, user, password):
    self.opener = opener
    self.user = user
    self.password = password

  def open(self, url, data, timeout):
    if isinstance(url, str):
      # if given a url - create a request and add
      req = urllib2.Request(url, data, {
                      "Authorization": 
                        "Basic " + base64.b64encode(
                           self.user + ":" + self.password)
                     })
    else:
      req = url
    return self.opener.open(req, data, timeout)

  def __getattr__(self, attr):
    if attr == "open":
      return self.open
    return getattr(self.opener, attr)


def RegisterPasswords(user, password):
  password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
  password_manager.add_password(
    None, 'https://rt.mycorp.site/', user, password)
  password_manager.add_password(
    None, 'https://jira.mycorp.site/', user, password)
  auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
  opener = urllib2.build_opener(auth_handler)
  # Jira has a strage behviour - it does not return the proper error 
  # when sending a request without an Authentication header.
  # This causes Python's urllib2 not to retry with the pass word.
  # For Jira we would need to add the headers all the time
  jira_opener = JiraOpenerWrapper(opener, user, password)
  urllib2.install_opener(jira_opener)


def GameJira():
  url = "https://jira.mycorp.site/rest/api/2/issue/PRJ-123"

  data = urllib2.urlopen(url, None).read()
  print "Jira:\n", data

  ask by kamal translate from so

未解决问题?本站智能推荐:

2回复

JIRA REST API和kerberos身份验证

我正在努力通过kerberos进行Jira REST API身份验证。 基本身份验证按预期工作。 如果我使用Web浏览器访问登录页面(在我使用kinit之后),然后在我的python脚本中使用生成的JSESSIONID,我可以使用REST而不会获得401.但是我没有使用我的python脚
1回复

JIRA-Python的基本身份验证不再适用于REST API调用。 接下来是什么?

在Python中,我曾经能够使用一些简单的代码通过REST对JIRA进行身份验证: 然后能够做一些简单的事情: 但是JIRA已经改变了一些东西,我猜不再允许通过REST API进行这样的基本身份验证。 相反,我得到401错误。 我厌倦了创建一个API令牌,如下所示: ht
1回复

为什么使用urllib2 python库时,与使用浏览器时相比,worldcat REST API返回响应所花的时间要长得多?

我正在使用worldcat python软件包,该软件包使用worldcat开放式REST API,并使用搜索查询和其他参数来获取图书数据。 其中_query_url是由基本url和一些参数(例如搜索字符串,每页记录数等)组成的url。通过使用timeit包,我发现每次调用API花费了1
2回复

使用Python和urllib2进行Windows身份验证

我想从需要我的Windows用户名和密码的网页上获取一些数据。 到目前为止,我有: 这是urllib2支持的吗? 我找到了Python NTLM ,但这需要我输入我的用户名和密码。有没有办法只是以某种方式获取身份验证信息(例如IE,或Firefox,如果我更改了network.a
1回复

无法使用REST API的Python使用liburl2进行删除

好的,所以我正在使用与此代码非常相似的代码( https://gist.github.com/metadaddy-sfdc/1374762 )获取身份验证令牌,并使用libur2进行简单查询,将python中的其余api用于销售人员数据库,但是当我尝试遵循此答案中给出的说明时, 如何使用urll
1回复

通过Python REST API执行JIRA过渡

如何使用Python通过其REST API (版本2)将JIRA问题标记为已解决或已 解决 ? 我在http://docs.atlassian.com/jira/REST/latest/#id199544上找到了文档,但是我遇到了许多错误,包括: HTTP错误415:不支持的媒体
2回复

Python / Rest中的身份验证问题

我的问题是,我不断收到“响应[401]”,从网上看到的内容来看,这意味着存在验证错误。 我正在尝试通过python中的Rest调用创建一个新用户。 我对Python / Rest相当陌生,因此我确定我缺少一些东西。 下面是我的代码: encodeString返回b'string
1回复

如何使用REST API从Python脚本更新Jira v5.1中的问题

我希望能够使用REST api从Python脚本更新Jira v5.1中的问题。 我有以下代码来提取现有问题的信息,它完美地运作: 我想扩展这个以便能够更新同一个问题,我有以下代码: 当我尝试执行代码时,收到以下错误消息: 并且错误指向我的代码中的“fp = opene
1回复

使用urllib2下载网页会导致垃圾乱码? (只是有时)

为什么我点击这个网页,我得到HTML文字: 但是当我点击这个网页时,我的垃圾乱了? 我在python中使用相同的download()函数,它在这里:
1回复

使用Python REST API在JIRA中创建问题和自定义字段

我正在使用JIRA Python模块(它是REST API的扩展)来自动执行JIRA中删除和创建问题的过程。 我正在尝试在python脚本中使用“ for”循环在JIRA中创建问题,该循环使用从其他数据库收集的导入数据。 创建问题时,我需要格式化字段,以便我拥有的数据可以与JIRA中的相应字