【问题标题】:How to authenticate in Jenkins while remotely accessing its JSON API?如何在远程访问其 JSON API 时在 Jenkins 中进行身份验证?
【发布时间】:2017-01-30 03:08:36
【问题描述】:

我需要从 Python 脚本访问 Jenkins JSON API。问题是我们的 Jenkins 安装是安全的,因此要登录用户必须选择一个证书。可悲的是,在 Jenkins Remote Access Documentation 他们没有提到关于证书的事情,我尝试使用 API 令牌但没有成功。

如何通过 Python 脚本进行身份验证以使用他们的 JSON API?

提前致谢!

【问题讨论】:

    标签: python authentication jenkins


    【解决方案1】:

    您必须使用 HTTP Basic Auth 对 JSON API 进行身份验证。

    要使脚本化客户端(例如 wget)调用需要授权的操作(例如调度构建),请使用 HTTP BASIC 身份验证来指定用户名和 API 令牌。这通常比模拟基于表单的身份验证更方便

    https://wiki.jenkins-ci.org/display/JENKINS/Authenticating+scripted+clients

    这是一个使用 Python 的基本身份验证示例。

    http://docs.python-requests.org/en/master/user/authentication/

    请记住,如果您在内部 Jenkins 服务器上使用自签名证书,则需要关闭证书验证从服务器获取证书并将其添加到 HTTP 请求中

    http://docs.python-requests.org/en/master/user/advanced/

    【讨论】:

    • 我必须使用证书 :( 但是非常感谢提供了如何在 Python 中使用证书的链接!我是 Python 新手!
    【解决方案2】:

    我终于找到了如何使用 certs 和 wget 对 Jenkins 进行身份验证。我必须将我的 pfx 证书转换为 pem 证书,并将证书和密钥放在单独的文件 For more info about that come here 中。最后这是我使用的命令。

    wget --certificate=/home/B/cert.pem --private-key=/home/B/key.pem --no-check-certificate --output-document=jenkins.json https:<URL>
    

    【讨论】:

      【解决方案3】:

      我不完全确定它是否涵盖了您的证书用例,但由于我花了一些时间才发现,我仍然想分享这个片段,它可以在没有特殊 Jenkins 库的情况下在 Python 中检索给定用户名的电子邮件地址.它使用 API 令牌并“支持”(实际上忽略了)https:

      def _get_email_adress(user):
          request = urllib.request.Request("https://jenkins_server/user/"+ user +"/api/json")
          #according to https://stackoverflow.com/a/28052583/4609258 the following is ugly
          context = ssl._create_unverified_context() 
          base64string = base64.b64encode(bytes('%s:%s' % ('my user name', 'my API token'),'ascii'))
          request.add_header("Authorization", "Basic %s" % base64string.decode('utf-8'))
      
          with urllib.request.urlopen(request, context=context) as url:
              user_data = json.loads(url.read().decode())
              for property in user_data['property']:
                  if property["_class"]=="hudson.tasks.Mailer$UserProperty":
                      return property["address"];
      

      【讨论】:

        猜你喜欢
        • 2019-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-14
        • 1970-01-01
        相关资源
        最近更新 更多