Skip to main content
 首页 » 编程设计

python之尝试从在 docker 上运行的 jenkins 获取版本信息时获取 jenkins.BadHTTPException

2025年05月04日24tintown

我为 Jenkins 版本安装了 docker 容器。 2.19.1.

docker ps 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                              NAMES 
f03c10935bb3        jenkins             "/bin/tini -- /usr/lo"   29 hours ago        Up 3 hours          0.0.0.0:8080->8080/tcp, 0.0.0.0:50000->50000/tcp   cocky_colden 

已安装 python-jenkins访问 jenkins 服务器的模块。

我尝试了 docs 中给出的第一个代码示例.

import jenkins 
 
server = jenkins.Jenkins('http://localhost:8080', username='admin', password='mytoken') 
user = server.get_whoami() 
version = server.get_version() 
print('Hello %s from Jenkins %s' % (user['fullName'], version)) 

但是它给出了错误。

python /tmp/test.py 
Traceback (most recent call last): 
  File "/tmp/test.py", line 5, in <module> 
    version = server.get_version() 
  File "/usr/lib/python2.7/site-packages/jenkins/__init__.py", line 616, in get_version 
    % self.server) 
jenkins.BadHTTPException: Error communicating with server[http://localhost:8080/] 

我查看了提到的文档:

From Jenkins vesion 1.426 onward you can specify an API token instead of your real password while authenticating the user against the Jenkins instance.

我使用了密码而不是 token 但得到了同样的错误。

我试过 curl

curl -X POST http://localhost:8080/job/testjob/build \ 
> --data token=mytoken \ 
> --data-urlencode json='{"parameter": [{"name":"id", "value":"123"}, {"name":"verbosity", "value":"high"}]}' 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
<title>Error 403 No valid crumb was included in the request</title> 
</head> 
<body><h2>HTTP ERROR 403</h2> 
<p>Problem accessing /job/testjob/build. Reason: 
<pre>    No valid crumb was included in the request</pre></p><hr><i><small>Powered by Jetty://</small></i><hr/> 
 
</body> 
</html> 

我从Name-> Configure -> Show API Token...获取 token

还有什么我必须从 Jenkins 方面启用才能访问吗?意思是,API 可以访问这个服务器?

请您参考如下方法:

get_version() 函数中似乎存在一个小错误。

如果 Jenkins 服务器设置为启用了安全性并且匿名用户没有“整体读取”权限,那么您需要将授权 key 传递给 urlopen()

即在文件“jenkins/__init__.py”中,get_version() 函数需要更改为:

def get_version(self): 
    try: 
        request = Request(self._build_url('')) 
        request.add_header('X-Jenkins', '0.0') 
        response = urlopen(request, timeout=self.timeout) 

收件人:

def get_version(self): 
    try: 
        request = Request(self._build_url('')) 
        if self.auth: 
            request.add_header('Authorization', self.auth) 
        request.add_header('X-Jenkins', '0.0') 
        response = urlopen(request, timeout=self.timeout) 

要查找此模块在您系统上的位置,请运行 python 并输入:

import jenkins 
jenkins.__file__ 

(我已将错误报告给模块作者)