我有一个通过自签名证书使用SSL的普通服务器。我试图使用Python 3.4.2 SSL套接字库创建连接并通过以下脚本返回数据并带有相关错误:
import socket, ssl
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ssl_socket = ssl.wrap_socket(s, keyfile="/path/to/server.pem", certfile="/path/to/client.pem", cert_reqs=ssl.CERT_REQUIRED, ssl_version=ssl.PROTOCOL_TLSv1_2, ca_certs="/path/to/client.pem")
ssl_socket.connect(('hostname', port))
ssl_socket.send("data_string".encode())
# returns '4' (number of returned bytes)
ssl_socket.setblocking(0) # turn off blocking
ssl_socket.recv(4096)
# error: ssl.SSLWantReadError: The operation did not complete (read) (_ssl.c:1960)
如果我没有将阻止设置为0,它就会挂起。我做了足够多的研究,发现它与返回数据的大小有关,但我在调用ssl_socket.send()
时获得了4个字节的返回值,所以我'我不确定我错过了什么。
请注意,我有一个perl客户端,它可以正常工作,如下所示:
#!/usr/bin/env perl
use IO::Socket::INET;
use IO::Socket::SSL;
# auto-flush on socket
$| = 1;
# create a connecting socket
my $socket = new IO::Socket::SSL (
PeerHost => 'hostname',
PeerPort => '12345',
Proto => 'tcp',
SSL_cert_file => $ENV{'HOME'} . '/path/to/client.pem',
SSL_key_file => $ENV{'HOME'} . '/path/to/server.pem',
);
die "cannot connect to the server $!\n" unless $socket;
print "connected to the server\n";
# data to send to a server
my $req = 'data';
print $socket "$req\n";
my @r = ( <$socket> ) ;
print "@r";
$socket->close();
输出:
connected to the server
{
"password": "passwd",
"username": "username"
}
使用Python SSL库检索我请求的数据的正确方法是什么?
答案 0 :(得分:0)
答案:我的数据字符串末尾需要一个'\n'
字符。