自 python 2.7 更新以来 urllib2 的基本身份验证错误

Basic authentication error with urllib2 since python 2.7 update

这段 python 代码在我 运行 我的 raspberry pi.

上进行 apt-get 升级之前一个小时前运行良好

现在这是我的 python 版本:Python 2.7.9(默认,2016 年 9 月 17 日,20:26:04)

import urllib, urllib2
from PIL import Image

URL="http://server.local/picture.jpg"
headers = {'Authorization': 'Basic ' + base64.encodestring('Guess:Thepassword')}
req = urllib2.Request(URL, None, headers)
img=Image.open(urllib2.urlopen(req,timeout=1))

但现在我得到这个错误:

File "/usr/lib/python2.7/httplib.py", line 1017, in putheader
raise ValueError('Invalid header value %r' % (one_value,))
ValueError: Invalid header value 'Basic TGlvbjpSdW5SYWJiaXRSdW4=\n'

我假设发生了一些变化,但无法弄清楚是什么..

您的 header 末尾不能有换行符 \n。不要使用 base64.encodestring,而是使用 base64.b64encode.

我认为这与 Python 的更新没有任何关系,因为自从 base64 模块被包含在 Python 2.4 中以来,这种行为就一直存在(请参阅粗体文本):

Encode the string s, which can contain arbitrary binary data, and return a string containing one or more lines of base64-encoded data. encodestring() returns a string containing one or more lines of base64-encoded data always including an extra trailing newline ('\n').

仅供参考 - 我相信功能的变化可以追溯到这个安全更新: https://launchpad.net/ubuntu/+source/python2.7/2.7.6-8ubuntu0.3:

SECURITY UPDATE: CRLF injection vulnerability in the
HTTPConnection.putheader
- debian/patches/CVE-2016-5699.patch: disallow newlines in
  putheader() arguments when not followed by spaces or tabs in
  Lib/httplib.py, add tests in Lib/test/test_httplib.py
- CVE-2016-5699