运行 Jenkins 工作在 Python 使用令牌

Run Jenkins Job In Python Using Token

我想 运行 Jenkins job 使用令牌。 但是这段代码给出了 403 错误。

如何避免这个问题?我不会使用用户名和密码,只有令牌。 有什么办法吗?

代码:

import requests
try:
    build = requests.get("http://jenkins_url/jenkins_job_name/build?token=TokenFromJob")
except Exception as e:
    print ("Failed triggering the Jenkins job")
print (build.status_code)

参考this。詹金斯不做授权。因此,即使在生成授权密钥之后,您仍需要在 python 脚本中处理授权。

Note that Jenkins does not do any authorization negotiation. i.e. it immediately returns a 403 (Forbidden) response instead of a 401 (Unauthorized) response, so make sure to send the authentication information from the first request (aka "preemptive authentication").

这是我的设置。需要传递用户名和 api 令牌,如下所示。登录后,您无需将令牌传递给构建 url。

import requests
from requests.auth import HTTPBasicAuth

session = requests.Session()
login_response = session.post(JENKINS_URL,auth=HTTPBasicAuth(USERNAME,API_TOKEN))
# check is status code is successfull
# then do other things
build = requests.get("http://jenkins_url/jenkins_job_name/build")
print (build.status_code)