【python】ImportError: No module named _ssl

深度链接 / 2023-12-06 21:48:36 / 270

python使用引入ssl时出现ImportError: No module named _ssl

1、错误重现

[root@wrx install]# python3
Python 3.4.4 (default, Jun 18 2017, 18:37:40) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ssl
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.4/ssl.py", line 97, in <module>
    import _ssl             # if we can't import it, let the error propagate
ImportError: No module named '_ssl'

2、查看是否有安装OpenSSL且包完整

[root@wrx install]# rpm -qa | grep openssl*
openssh-5.3p1-118.1.el6_8.i686
openssh-clients-5.3p1-118.1.el6_8.i686
openssl-1.0.1e-48.el6_8.4.i686
openssh-server-5.3p1-118.1.el6_8.i686

#查询结果显示缺少OpenSSL-devel

3、使用yum安装openssl-devel

[root@wrx install]# yum install openssl-devel -y
#查看是否安装成功
[root@wrx install]# rpm -qa | grep openssl*
openssh-5.3p1-118.1.el6_8.i686
openssh-clients-5.3p1-118.1.el6_8.i686
openssl-1.0.1e-57.el6.i686
openssh-server-5.3p1-118.1.el6_8.i686
openssl-devel-1.0.1e-57.el6.i686 #存在

4、重新编译安装python3

#修改Setup文件
[root@wrx install]# vim /var/data/install/Python-3.4.4/Modules/Setup
#如果不知道Setup文件在哪,可以搜索下
[root@wrx install]# find / -name Setup
/var/data/install/Python-3.4.4/Modules/Setup
/usr/local/lib/python3.4/config-3.4m/Setup

#修改内容前
# Socket module helper for socket(2)
#_socket socketmodule.c

# Socket module helper for SSL support; you must comment out the other
# socket line above, and possibly edit the SSL variable:
#SSL=/usr/local/ssl
#_ssl _ssl.c \
#       -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
#       -L$(SSL)/lib -lssl -lcrypto

#修改后
# Socket module helper for socket(2)
_socket socketmodule.c

# Socket module helper for SSL support; you must comment out the other
# socket line above, and possibly edit the SSL variable:
#SSL=/usr/local/ssl
_ssl _ssl.c \
-DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
-L$(SSL)/lib -lssl -lcrypto

#重新编译安装
[root@wrx Python-3.4.4]# make
[root@wrx Python-3.4.4]# make install

5、查看ssl模块是否安装成功

[root@wrx Python-3.4.4]# python3
Python 3.4.4 (default, Jun 18 2017, 19:00:00) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ssl
>>> print(ssl.PROTOCOL_SSLv23)
2
>>> 

#没有报错说明已经安装成功