如何在 python 2.7.6 中导入 _ssl?

How to import _ssl in python 2.7.6?

我的 HTTP 服务器基于 Python 2.7.6 的 BaseHTTPServer。现在我想让它支持ssl传输,也就是所谓的https。

我已经安装了 pyOpenSSL 并重新编译了 python 支持 ssl 的源代码。当我在我的 python 解释器中尝试 import ssl 时它确实有效,但是当我 运行 我的服务器上的代码时它不起作用。错误日志是这样的:

import _ssl # if we can't import it, let the error propagate

看起来很奇怪,不是吗?我的操作系统是 Debian Linux 发行版。这几天网上能找到的各种方法都试过了,谁能帮我解决这个问题?


我试图直接在服务器代码中 "import _ssl",但它提醒我:

>>>callstack
Traceback (most recent call last):
  File "./script/main.py", line 85, in process
    net_flag = net_api_process()
  File "./script/core/netbase/interface.py", line 96, in net_api_process
    flag1 = network.instance().process()
  File "./script/core/netbase/network.py", line 271, in process
    if network.process(max_events):
  File "./script/core/netbase/network.py", line 75, in on_incomin_stream
    self.on_package(buf)
  File "./script/core/netbase/network.py", line 78, in on_package
    self.f_on_package(self, buf)
  File "./script/client/behavior.py", line 68, in on_package
    handler.OnPackage(pack, cmd, conn.m_uid, conn)
  File "./script/client/handler.py", line 288, in OnPackage
    func(uid, conn, pack)
  File "./script/logic/user_info/modify.py", line 365, in OnModBaseInfo
    ModBaseInfo(uid, conn, seq, json_str)
  File "./script/logic/user_info/modify.py", line 385, in ModBaseInfo
    modify_pub.Start()
  File "./script/logic/user_info/modify.py", line 253, in Start
    import _ssl
ImportError: No module named _ssl

我终于解决了这个问题! _ssl 模块是 python 的内置模块,但它需要在您的系统上安装 openssl。

先换成root用户! 1.Install openssl 和 libssl-dev。 如果在 debian 上 OS

apt-get install openssl
apt-get install libssl-dev

2.Recompile python

cd Python2.7.6
./configure
make && make install

但实际上,我是这样解决问题的! 1.Install openssl 我从网上下载了一个包,是openssl-1.0.2d.tar.gz

tar zxvf openssl-1.0.2d.tar.gz
cd openssl-1.0.2d
./config -fPIC   //configuration:create path independent libssl.a
make && make install

2.Recompile python2.7,并支持ssl模块

tar xvf Python-2.7.6.tar
cd Python-2.7.6
vim Modules/Setup.dist 

找到以下行并取消注释。(使用/ssl+Enter 可以在vim中快速找到这些行)

# Socket module helper for socket(2)
_socket socketmodule.c timemodule.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

然后配置和制作,制作安装

./configure --enable-shared //--enable-shared option means to generate dynamic library libpython2.7.so.1.0
make && make install

我们的项目依赖于libpython2.7.so.1.0。现在我可以 "import ssl" 或 "import _ssl" 在我的 python 脚本或 python 解释器中使用新的 libpython2.7.so.1.0.