46
try:
import ssl
except ImportError:
pass
else:
... # do something that requires SSL support
17.3.4.2. Client-side operation
This example connects to an SSL server, prints the server’s address and certificate,
sends some bytes, and reads part of the response:
import socket, ssl, pprint
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# require a certificate from the server
ssl_sock = ssl.wrap_socket(s,
ca_certs="/etc/ca_certs_file",
cert_reqs=ssl.CERT_REQUIRED)
ssl_sock.connect(('www.verisign.com', 443))
print repr(ssl_sock.getpeername())
print ssl_sock.cipher()
print pprint.pformat(ssl_sock.getpeercert())
# Set a simple HTTP request -- use httplib in actual code.
ssl_sock.write("""GET / HTTP/1.0\r
Host: www.verisign.com\r\n\r\n""")
# Read a chunk of data. Will not necessarily
# read all the data returned by the server.
data = ssl_sock.read()
# note that closing the SSLSocket will also close the underlying socket
ssl_sock.close()
As of September 6, 2007, the certificate printed by this program looked like this:
{'notAfter': 'May 8 23:59:59 2009 GMT',
'subject': ((('serialNumber', u'2497886'),),
(('1.3.6.1.4.1.311.60.2.1.3', u'US'),),
(('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'),),
(('countryName', u'US'),),
(('postalCode', u'94043'),),
(('stateOrProvinceName', u'California'),),
(('localityName', u'Mountain View'),),
(('streetAddress', u'487 East Middlefield Road'),),
(('organizationName', u'VeriSign, Inc.'),),
(('organizationalUnitName',
u'Production Security Services'),),
(('organizationalUnitName',
u'Terms of use at www.verisign.com/rpa (c)06'),),
(('commonName', u'www.verisign.com'),))}
which is a fairly poorly-formed
subject
field.