背景
首先, centos7 通过yum安装的openssl-devel包是1.0.2k的,这玩意儿太老了。我们选择从源码安装openssl。
centos7内置了二进制文件/usr/bin/openssl, 版本为1.0.2k,编译新版后直接删掉就行。
用途
python 3.10 及以上, 源码安装时,需要openssl1.1.1+
pip install requests>2.26时, 需要openssl1.1.1+
编译安装openssl1.1.1d
先去掉旧版ssldev的包yum remove openssl-devel openssl
备份旧版opensslmv /usr/bin/openssl /usr/bin/openssl1.0.2
(没有就跳过)
## 下载源码
wget --no-check-certificate https://www.openssl.org/source/openssl-1.1.1d.tar.gz
## 编译 (很快,就几分钟ok)
tar -zxvf openssl-1.1.1d.tar.gz
cd openssl-1.1.1d
mkdir -p /usr/local/openssl
./config --prefix=/usr/local/openssl no-zlib
make && make install
## 动态库链接
ln -s /usr/local/openssl/include/openssl /usr/include/openssl
ln -s /usr/local/openssl/lib/libssl.so.1.1 /usr/local/lib64/libssl.so
ln -s /usr/local/openssl/bin/openssl /usr/bin/openssl
## 配置ldconfig
echo "/usr/local/openssl/lib" >> /etc/ld.so.conf
ldconfig -v
测试centos的python2 ssl模块是否正常
能正常输出html就ok。
import urllib2
import ssl
url = "https://example.com"
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36' }
request = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(request, context=ssl.SSLContext(ssl.PROTOCOL_TLSv1))
html = response.read()
response.close()
print html
pyenv编译python3.10+需要配置环境变量(必须)
export CFLAGS="-I/usr/local/openssl/include"
export LDFLAGS="-L/usr/local/openssl/lib"
export PKG_CONFIG_PATH="/usr/local/openssl/lib/pkgconfig"
必须滴,不然会报错:
ModuleNotFoundError: No module named ‘_ssl’
ERROR: The Python ssl extension was not compiled. Missing the OpenSSL lib?
编译python前记得安装依赖
sudo yum groupinstall "Development Tools"
sudo yum install bzip2-devel libffi-devel zlib-devel readline-devel sqlite-devel xz-devel tk-devel gdbm-devel