### 导航
- [索引](../genindex.xhtml "总目录")
- [模块](../py-modindex.xhtml "Python 模块索引") |
- [下一页](select.xhtml "select --- Waiting for I/O completion") |
- [上一页](socket.xhtml "socket --- 底层网络接口") |
- ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png)
- [Python](https://www.python.org/) »
- zh\_CN 3.7.3 [文档](../index.xhtml) »
- [Python 标准库](index.xhtml) »
- [网络和进程间通信](ipc.xhtml) »
- $('.inline-search').show(0); |
# [`ssl`](#module-ssl "ssl: TLS/SSL wrapper for socket objects") --- TLS/SSL wrapper for socket objects
**Source code:** [Lib/ssl.py](https://github.com/python/cpython/tree/3.7/Lib/ssl.py) \[https://github.com/python/cpython/tree/3.7/Lib/ssl.py\]
- - - - - -
This module provides access to Transport Layer Security (often known as "Secure Sockets Layer") encryption and peer authentication facilities for network sockets, both client-side and server-side. This module uses the OpenSSL library. It is available on all modern Unix systems, Windows, Mac OS X, and probably additional platforms, as long as OpenSSL is installed on that platform.
注解
Some behavior may be platform dependent, since calls are made to the operating system socket APIs. The installed version of OpenSSL may also cause variations in behavior. For example, TLSv1.1 and TLSv1.2 come with openssl version 1.0.1.
警告
Don't use this module without reading the [Security considerations](#ssl-security). Doing so may lead to a false sense of security, as the default settings of the ssl module are not necessarily appropriate for your application.
This section documents the objects and functions in the `ssl` module; for more general information about TLS, SSL, and certificates, the reader is referred to the documents in the "See Also" section at the bottom.
This module provides a class, [`ssl.SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket"), which is derived from the [`socket.socket`](socket.xhtml#socket.socket "socket.socket") type, and provides a socket-like wrapper that also encrypts and decrypts the data going over the socket with SSL. It supports additional methods such as `getpeercert()`, which retrieves the certificate of the other side of the connection, and `cipher()`,which retrieves the cipher being used for the secure connection.
For more sophisticated applications, the [`ssl.SSLContext`](#ssl.SSLContext "ssl.SSLContext") class helps manage settings and certificates, which can then be inherited by SSL sockets created through the [`SSLContext.wrap_socket()`](#ssl.SSLContext.wrap_socket "ssl.SSLContext.wrap_socket") method.
在 3.5.3 版更改: Updated to support linking with OpenSSL 1.1.0
在 3.6 版更改: OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported. In the future the ssl module will require at least OpenSSL 1.0.2 or 1.1.0.
## Functions, Constants, and Exceptions
### Socket creation
Since Python 3.2 and 2.7.9, it is recommended to use the [`SSLContext.wrap_socket()`](#ssl.SSLContext.wrap_socket "ssl.SSLContext.wrap_socket") of an [`SSLContext`](#ssl.SSLContext "ssl.SSLContext") instance to wrap sockets as [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket") objects. The helper functions [`create_default_context()`](#ssl.create_default_context "ssl.create_default_context") returns a new context with secure default settings. The old [`wrap_socket()`](#ssl.wrap_socket "ssl.wrap_socket") function is deprecated since it is both inefficient and has no support for server name indication (SNI) and hostname matching.
Client socket example with default context and IPv4/IPv6 dual stack:
```
import socket
import ssl
hostname = 'www.python.org'
context = ssl.create_default_context()
with socket.create_connection((hostname, 443)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
print(ssock.version())
```
Client socket example with custom context and IPv4:
```
hostname = 'www.python.org'
# PROTOCOL_TLS_CLIENT requires valid cert chain and hostname
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.load_verify_locations('path/to/cabundle.pem')
with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
print(ssock.version())
```
Server socket example listening on localhost IPv4:
```
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key')
with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
sock.bind(('127.0.0.1', 8443))
sock.listen(5)
with context.wrap_socket(sock, server_side=True) as ssock:
conn, addr = ssock.accept()
...
```
### Context creation
A convenience function helps create [`SSLContext`](#ssl.SSLContext "ssl.SSLContext") objects for common purposes.
`ssl.``create_default_context`(*purpose=Purpose.SERVER\_AUTH*, *cafile=None*, *capath=None*, *cadata=None*)Return a new [`SSLContext`](#ssl.SSLContext "ssl.SSLContext") object with default settings for the given *purpose*. The settings are chosen by the [`ssl`](#module-ssl "ssl: TLS/SSL wrapper for socket objects") module, and usually represent a higher security level than when calling the [`SSLContext`](#ssl.SSLContext "ssl.SSLContext") constructor directly.
*cafile*, *capath*, *cadata* represent optional CA certificates to trust for certificate verification, as in [`SSLContext.load_verify_locations()`](#ssl.SSLContext.load_verify_locations "ssl.SSLContext.load_verify_locations"). If all three are [`None`](constants.xhtml#None "None"), this function can choose to trust the system's default CA certificates instead.
The settings are: [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS"), [`OP_NO_SSLv2`](#ssl.OP_NO_SSLv2 "ssl.OP_NO_SSLv2"), and [`OP_NO_SSLv3`](#ssl.OP_NO_SSLv3 "ssl.OP_NO_SSLv3") with high encryption cipher suites without RC4 and without unauthenticated cipher suites. Passing [`SERVER_AUTH`](#ssl.Purpose.SERVER_AUTH "ssl.Purpose.SERVER_AUTH")as *purpose* sets [`verify_mode`](#ssl.SSLContext.verify_mode "ssl.SSLContext.verify_mode") to [`CERT_REQUIRED`](#ssl.CERT_REQUIRED "ssl.CERT_REQUIRED")and either loads CA certificates (when at least one of *cafile*, *capath* or *cadata* is given) or uses [`SSLContext.load_default_certs()`](#ssl.SSLContext.load_default_certs "ssl.SSLContext.load_default_certs") to load default CA certificates.
注解
The protocol, options, cipher and other settings may change to more restrictive values anytime without prior deprecation. The values represent a fair balance between compatibility and security.
If your application needs specific settings, you should create a [`SSLContext`](#ssl.SSLContext "ssl.SSLContext") and apply the settings yourself.
注解
If you find that when certain older clients or servers attempt to connect with a [`SSLContext`](#ssl.SSLContext "ssl.SSLContext") created by this function that they get an error stating "Protocol or cipher suite mismatch", it may be that they only support SSL3.0 which this function excludes using the [`OP_NO_SSLv3`](#ssl.OP_NO_SSLv3 "ssl.OP_NO_SSLv3"). SSL3.0 is widely considered to be [completely broken](https://en.wikipedia.org/wiki/POODLE) \[https://en.wikipedia.org/wiki/POODLE\]. If you still wish to continue to use this function but still allow SSL 3.0 connections you can re-enable them using:
```
ctx = ssl.create_default_context(Purpose.CLIENT_AUTH)
ctx.options &= ~ssl.OP_NO_SSLv3
```
3\.4 新版功能.
在 3.4.4 版更改: RC4 was dropped from the default cipher string.
在 3.6 版更改: ChaCha20/Poly1305 was added to the default cipher string.
3DES was dropped from the default cipher string.
### 异常
*exception* `ssl.``SSLError`Raised to signal an error from the underlying SSL implementation (currently provided by the OpenSSL library). This signifies some problem in the higher-level encryption and authentication layer that's superimposed on the underlying network connection. This error is a subtype of [`OSError`](exceptions.xhtml#OSError "OSError"). The error code and message of [`SSLError`](#ssl.SSLError "ssl.SSLError") instances are provided by the OpenSSL library.
在 3.3 版更改: [`SSLError`](#ssl.SSLError "ssl.SSLError") used to be a subtype of [`socket.error`](socket.xhtml#socket.error "socket.error").
`library`A string mnemonic designating the OpenSSL submodule in which the error occurred, such as `SSL`, `PEM` or `X509`. The range of possible values depends on the OpenSSL version.
3\.3 新版功能.
`reason`A string mnemonic designating the reason this error occurred, for example `CERTIFICATE_VERIFY_FAILED`. The range of possible values depends on the OpenSSL version.
3\.3 新版功能.
*exception* `ssl.``SSLZeroReturnError`A subclass of [`SSLError`](#ssl.SSLError "ssl.SSLError") raised when trying to read or write and the SSL connection has been closed cleanly. Note that this doesn't mean that the underlying transport (read TCP) has been closed.
3\.3 新版功能.
*exception* `ssl.``SSLWantReadError`A subclass of [`SSLError`](#ssl.SSLError "ssl.SSLError") raised by a [non-blocking SSL socket](#ssl-nonblocking) when trying to read or write data, but more data needs to be received on the underlying TCP transport before the request can be fulfilled.
3\.3 新版功能.
*exception* `ssl.``SSLWantWriteError`A subclass of [`SSLError`](#ssl.SSLError "ssl.SSLError") raised by a [non-blocking SSL socket](#ssl-nonblocking) when trying to read or write data, but more data needs to be sent on the underlying TCP transport before the request can be fulfilled.
3\.3 新版功能.
*exception* `ssl.``SSLSyscallError`A subclass of [`SSLError`](#ssl.SSLError "ssl.SSLError") raised when a system error was encountered while trying to fulfill an operation on a SSL socket. Unfortunately, there is no easy way to inspect the original errno number.
3\.3 新版功能.
*exception* `ssl.``SSLEOFError`A subclass of [`SSLError`](#ssl.SSLError "ssl.SSLError") raised when the SSL connection has been terminated abruptly. Generally, you shouldn't try to reuse the underlying transport when this error is encountered.
3\.3 新版功能.
*exception* `ssl.``SSLCertVerificationError`A subclass of [`SSLError`](#ssl.SSLError "ssl.SSLError") raised when certificate validation has failed.
3\.7 新版功能.
`verify_code`A numeric error number that denotes the verification error.
`verify_message`A human readable string of the verification error.
*exception* `ssl.``CertificateError`An alias for [`SSLCertVerificationError`](#ssl.SSLCertVerificationError "ssl.SSLCertVerificationError").
在 3.7 版更改: The exception is now an alias for [`SSLCertVerificationError`](#ssl.SSLCertVerificationError "ssl.SSLCertVerificationError").
### Random generation
`ssl.``RAND_bytes`(*num*)Return *num* cryptographically strong pseudo-random bytes. Raises an [`SSLError`](#ssl.SSLError "ssl.SSLError") if the PRNG has not been seeded with enough data or if the operation is not supported by the current RAND method. [`RAND_status()`](#ssl.RAND_status "ssl.RAND_status")can be used to check the status of the PRNG and [`RAND_add()`](#ssl.RAND_add "ssl.RAND_add") can be used to seed the PRNG.
For almost all applications [`os.urandom()`](os.xhtml#os.urandom "os.urandom") is preferable.
Read the Wikipedia article, [Cryptographically secure pseudorandom number generator (CSPRNG)](https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator) \[https://en.wikipedia.org/wiki/Cryptographically\_secure\_pseudorandom\_number\_generator\], to get the requirements of a cryptographically generator.
3\.3 新版功能.
`ssl.``RAND_pseudo_bytes`(*num*)Return (bytes, is\_cryptographic): bytes are *num* pseudo-random bytes, is\_cryptographic is `True` if the bytes generated are cryptographically strong. Raises an [`SSLError`](#ssl.SSLError "ssl.SSLError") if the operation is not supported by the current RAND method.
Generated pseudo-random byte sequences will be unique if they are of sufficient length, but are not necessarily unpredictable. They can be used for non-cryptographic purposes and for certain purposes in cryptographic protocols, but usually not for key generation etc.
For almost all applications [`os.urandom()`](os.xhtml#os.urandom "os.urandom") is preferable.
3\.3 新版功能.
3\.6 版后已移除: OpenSSL has deprecated [`ssl.RAND_pseudo_bytes()`](#ssl.RAND_pseudo_bytes "ssl.RAND_pseudo_bytes"), use [`ssl.RAND_bytes()`](#ssl.RAND_bytes "ssl.RAND_bytes") instead.
`ssl.``RAND_status`()Return `True` if the SSL pseudo-random number generator has been seeded with 'enough' randomness, and `False` otherwise. You can use [`ssl.RAND_egd()`](#ssl.RAND_egd "ssl.RAND_egd") and [`ssl.RAND_add()`](#ssl.RAND_add "ssl.RAND_add") to increase the randomness of the pseudo-random number generator.
`ssl.``RAND_egd`(*path*)If you are running an entropy-gathering daemon (EGD) somewhere, and *path*is the pathname of a socket connection open to it, this will read 256 bytes of randomness from the socket, and add it to the SSL pseudo-random number generator to increase the security of generated secret keys. This is typically only necessary on systems without better sources of randomness.
See <http://egd.sourceforge.net/> or <http://prngd.sourceforge.net/> for sources of entropy-gathering daemons.
[Availability](intro.xhtml#availability): not available with LibreSSL and OpenSSL > 1.1.0.
`ssl.``RAND_add`(*bytes*, *entropy*)Mix the given *bytes* into the SSL pseudo-random number generator. The parameter *entropy* (a float) is a lower bound on the entropy contained in string (so you can always use `0.0`). See [**RFC 1750**](https://tools.ietf.org/html/rfc1750.html) \[https://tools.ietf.org/html/rfc1750.html\] for more information on sources of entropy.
在 3.5 版更改: Writable [bytes-like object](../glossary.xhtml#term-bytes-like-object) is now accepted.
### Certificate handling
`ssl.``match_hostname`(*cert*, *hostname*)Verify that *cert* (in decoded format as returned by [`SSLSocket.getpeercert()`](#ssl.SSLSocket.getpeercert "ssl.SSLSocket.getpeercert")) matches the given *hostname*. The rules applied are those for checking the identity of HTTPS servers as outlined in [**RFC 2818**](https://tools.ietf.org/html/rfc2818.html) \[https://tools.ietf.org/html/rfc2818.html\], [**RFC 5280**](https://tools.ietf.org/html/rfc5280.html) \[https://tools.ietf.org/html/rfc5280.html\] and [**RFC 6125**](https://tools.ietf.org/html/rfc6125.html) \[https://tools.ietf.org/html/rfc6125.html\]. In addition to HTTPS, this function should be suitable for checking the identity of servers in various SSL-based protocols such as FTPS, IMAPS, POPS and others.
[`CertificateError`](#ssl.CertificateError "ssl.CertificateError") is raised on failure. On success, the function returns nothing:
```
>>> cert = {'subject': ((('commonName', 'example.com'),),)}
>>> ssl.match_hostname(cert, "example.com")
>>> ssl.match_hostname(cert, "example.org")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'
```
3\.2 新版功能.
在 3.3.3 版更改: The function now follows [**RFC 6125**](https://tools.ietf.org/html/rfc6125.html) \[https://tools.ietf.org/html/rfc6125.html\], section 6.4.3 and does neither match multiple wildcards (e.g. `*.*.com` or `*a*.example.org`) nor a wildcard inside an internationalized domain names (IDN) fragment. IDN A-labels such as `www*.xn--pthon-kva.org` are still supported, but `x*.python.org` no longer matches `xn--tda.python.org`.
在 3.5 版更改: Matching of IP addresses, when present in the subjectAltName field of the certificate, is now supported.
在 3.7 版更改: The function is no longer used to TLS connections. Hostname matching is now performed by OpenSSL.
Allow wildcard when it is the leftmost and the only character in that segment. Partial wildcards like `www*.example.com` are no longer supported.
3\.7 版后已移除.
`ssl.``cert_time_to_seconds`(*cert\_time*)Return the time in seconds since the Epoch, given the `cert_time`string representing the "notBefore" or "notAfter" date from a certificate in `"%b %d %H:%M:%S %Y %Z"` strptime format (C locale).
Here's an example:
```
>>> import ssl
>>> timestamp = ssl.cert_time_to_seconds("Jan 5 09:34:43 2018 GMT")
>>> timestamp
1515144883
>>> from datetime import datetime
>>> print(datetime.utcfromtimestamp(timestamp))
2018-01-05 09:34:43
```
"notBefore" or "notAfter" dates must use GMT ([**RFC 5280**](https://tools.ietf.org/html/rfc5280.html) \[https://tools.ietf.org/html/rfc5280.html\]).
在 3.5 版更改: Interpret the input time as a time in UTC as specified by 'GMT' timezone in the input string. Local timezone was used previously. Return an integer (no fractions of a second in the input format)
`ssl.``get_server_certificate`(*addr*, *ssl\_version=PROTOCOL\_TLS*, *ca\_certs=None*)Given the address `addr` of an SSL-protected server, as a (*hostname*, *port-number*) pair, fetches the server's certificate, and returns it as a PEM-encoded string. If `ssl_version` is specified, uses that version of the SSL protocol to attempt to connect to the server. If `ca_certs` is specified, it should be a file containing a list of root certificates, the same format as used for the same parameter in [`SSLContext.wrap_socket()`](#ssl.SSLContext.wrap_socket "ssl.SSLContext.wrap_socket"). The call will attempt to validate the server certificate against that set of root certificates, and will fail if the validation attempt fails.
在 3.3 版更改: This function is now IPv6-compatible.
在 3.5 版更改: The default *ssl\_version* is changed from [`PROTOCOL_SSLv3`](#ssl.PROTOCOL_SSLv3 "ssl.PROTOCOL_SSLv3") to [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS") for maximum compatibility with modern servers.
`ssl.``DER_cert_to_PEM_cert`(*DER\_cert\_bytes*)Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded string version of the same certificate.
`ssl.``PEM_cert_to_DER_cert`(*PEM\_cert\_string*)Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of bytes for that same certificate.
`ssl.``get_default_verify_paths`()Returns a named tuple with paths to OpenSSL's default cafile and capath. The paths are the same as used by [`SSLContext.set_default_verify_paths()`](#ssl.SSLContext.set_default_verify_paths "ssl.SSLContext.set_default_verify_paths"). The return value is a [named tuple](../glossary.xhtml#term-named-tuple)`DefaultVerifyPaths`:
- `cafile` - resolved path to cafile or `None` if the file doesn't exist,
- `capath` - resolved path to capath or `None` if the directory doesn't exist,
- `openssl_cafile_env` - OpenSSL's environment key that points to a cafile,
- `openssl_cafile` - hard coded path to a cafile,
- `openssl_capath_env` - OpenSSL's environment key that points to a capath,
- `openssl_capath` - hard coded path to a capath directory
[Availability](intro.xhtml#availability): LibreSSL ignores the environment vars `openssl_cafile_env` and `openssl_capath_env`.
3\.4 新版功能.
`ssl.``enum_certificates`(*store\_name*)Retrieve certificates from Windows' system cert store. *store\_name* may be one of `CA`, `ROOT` or `MY`. Windows may provide additional cert stores, too.
The function returns a list of (cert\_bytes, encoding\_type, trust) tuples. The encoding\_type specifies the encoding of cert\_bytes. It is either `x509_asn` for X.509 ASN.1 data or `pkcs_7_asn` for PKCS#7 ASN.1 data. Trust specifies the purpose of the certificate as a set of OIDS or exactly `True` if the certificate is trustworthy for all purposes.
示例:
```
>>> ssl.enum_certificates("CA")
[(b'data...', 'x509_asn', {'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'}),
(b'data...', 'x509_asn', True)]
```
[可用性](intro.xhtml#availability): Windows。
3\.4 新版功能.
`ssl.``enum_crls`(*store\_name*)Retrieve CRLs from Windows' system cert store. *store\_name* may be one of `CA`, `ROOT` or `MY`. Windows may provide additional cert stores, too.
The function returns a list of (cert\_bytes, encoding\_type, trust) tuples. The encoding\_type specifies the encoding of cert\_bytes. It is either `x509_asn` for X.509 ASN.1 data or `pkcs_7_asn` for PKCS#7 ASN.1 data.
[可用性](intro.xhtml#availability): Windows。
3\.4 新版功能.
`ssl.``wrap_socket`(*sock*, *keyfile=None*, *certfile=None*, *server\_side=False*, *cert\_reqs=CERT\_NONE*, *ssl\_version=PROTOCOL\_TLS*, *ca\_certs=None*, *do\_handshake\_on\_connect=True*, *suppress\_ragged\_eofs=True*, *ciphers=None*)Takes an instance `sock` of [`socket.socket`](socket.xhtml#socket.socket "socket.socket"), and returns an instance of [`ssl.SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket"), a subtype of [`socket.socket`](socket.xhtml#socket.socket "socket.socket"), which wraps the underlying socket in an SSL context. `sock` must be a [`SOCK_STREAM`](socket.xhtml#socket.SOCK_STREAM "socket.SOCK_STREAM") socket; other socket types are unsupported.
Internally, function creates a [`SSLContext`](#ssl.SSLContext "ssl.SSLContext") with protocol *ssl\_version* and [`SSLContext.options`](#ssl.SSLContext.options "ssl.SSLContext.options") set to *cert\_reqs*. If parameters *keyfile*, *certfile*, *ca\_certs* or *ciphers* are set, then the values are passed to [`SSLContext.load_cert_chain()`](#ssl.SSLContext.load_cert_chain "ssl.SSLContext.load_cert_chain"), [`SSLContext.load_verify_locations()`](#ssl.SSLContext.load_verify_locations "ssl.SSLContext.load_verify_locations"), and [`SSLContext.set_ciphers()`](#ssl.SSLContext.set_ciphers "ssl.SSLContext.set_ciphers").
The arguments *server\_side*, *do\_handshake\_on\_connect*, and *suppress\_ragged\_eofs* have the same meaning as [`SSLContext.wrap_socket()`](#ssl.SSLContext.wrap_socket "ssl.SSLContext.wrap_socket").
3\.7 版后已移除: Since Python 3.2 and 2.7.9, it is recommended to use the [`SSLContext.wrap_socket()`](#ssl.SSLContext.wrap_socket "ssl.SSLContext.wrap_socket") instead of [`wrap_socket()`](#ssl.wrap_socket "ssl.wrap_socket"). The top-level function is limited and creates an insecure client socket without server name indication or hostname matching.
### 常数
> All constants are now [`enum.IntEnum`](enum.xhtml#enum.IntEnum "enum.IntEnum") or [`enum.IntFlag`](enum.xhtml#enum.IntFlag "enum.IntFlag") collections.
>
> 3\.6 新版功能.
`ssl.``CERT_NONE`Possible value for [`SSLContext.verify_mode`](#ssl.SSLContext.verify_mode "ssl.SSLContext.verify_mode"), or the `cert_reqs`parameter to [`wrap_socket()`](#ssl.wrap_socket "ssl.wrap_socket"). Except for [`PROTOCOL_TLS_CLIENT`](#ssl.PROTOCOL_TLS_CLIENT "ssl.PROTOCOL_TLS_CLIENT"), it is the default mode. With client-side sockets, just about any cert is accepted. Validation errors, such as untrusted or expired cert, are ignored and do not abort the TLS/SSL handshake.
In server mode, no certificate is requested from the client, so the client does not send any for client cert authentication.
See the discussion of [Security considerations](#ssl-security) below.
`ssl.``CERT_OPTIONAL`Possible value for [`SSLContext.verify_mode`](#ssl.SSLContext.verify_mode "ssl.SSLContext.verify_mode"), or the `cert_reqs`parameter to [`wrap_socket()`](#ssl.wrap_socket "ssl.wrap_socket"). In client mode, [`CERT_OPTIONAL`](#ssl.CERT_OPTIONAL "ssl.CERT_OPTIONAL")has the same meaning as [`CERT_REQUIRED`](#ssl.CERT_REQUIRED "ssl.CERT_REQUIRED"). It is recommended to use [`CERT_REQUIRED`](#ssl.CERT_REQUIRED "ssl.CERT_REQUIRED") for client-side sockets instead.
In server mode, a client certificate request is sent to the client. The client may either ignore the request or send a certificate in order perform TLS client cert authentication. If the client chooses to send a certificate, it is verified. Any verification error immediately aborts the TLS handshake.
Use of this setting requires a valid set of CA certificates to be passed, either to [`SSLContext.load_verify_locations()`](#ssl.SSLContext.load_verify_locations "ssl.SSLContext.load_verify_locations") or as a value of the `ca_certs` parameter to [`wrap_socket()`](#ssl.wrap_socket "ssl.wrap_socket").
`ssl.``CERT_REQUIRED`Possible value for [`SSLContext.verify_mode`](#ssl.SSLContext.verify_mode "ssl.SSLContext.verify_mode"), or the `cert_reqs`parameter to [`wrap_socket()`](#ssl.wrap_socket "ssl.wrap_socket"). In this mode, certificates are required from the other side of the socket connection; an [`SSLError`](#ssl.SSLError "ssl.SSLError")will be raised if no certificate is provided, or if its validation fails. This mode is **not** sufficient to verify a certificate in client mode as it does not match hostnames. [`check_hostname`](#ssl.SSLContext.check_hostname "ssl.SSLContext.check_hostname") must be enabled as well to verify the authenticity of a cert. [`PROTOCOL_TLS_CLIENT`](#ssl.PROTOCOL_TLS_CLIENT "ssl.PROTOCOL_TLS_CLIENT") uses [`CERT_REQUIRED`](#ssl.CERT_REQUIRED "ssl.CERT_REQUIRED") and enables [`check_hostname`](#ssl.SSLContext.check_hostname "ssl.SSLContext.check_hostname") by default.
With server socket, this mode provides mandatory TLS client cert authentication. A client certificate request is sent to the client and the client must provide a valid and trusted certificate.
Use of this setting requires a valid set of CA certificates to be passed, either to [`SSLContext.load_verify_locations()`](#ssl.SSLContext.load_verify_locations "ssl.SSLContext.load_verify_locations") or as a value of the `ca_certs` parameter to [`wrap_socket()`](#ssl.wrap_socket "ssl.wrap_socket").
*class* `ssl.``VerifyMode`[`enum.IntEnum`](enum.xhtml#enum.IntEnum "enum.IntEnum") collection of CERT\_\* constants.
3\.6 新版功能.
`ssl.``VERIFY_DEFAULT`Possible value for [`SSLContext.verify_flags`](#ssl.SSLContext.verify_flags "ssl.SSLContext.verify_flags"). In this mode, certificate revocation lists (CRLs) are not checked. By default OpenSSL does neither require nor verify CRLs.
3\.4 新版功能.
`ssl.``VERIFY_CRL_CHECK_LEAF`Possible value for [`SSLContext.verify_flags`](#ssl.SSLContext.verify_flags "ssl.SSLContext.verify_flags"). In this mode, only the peer cert is check but non of the intermediate CA certificates. The mode requires a valid CRL that is signed by the peer cert's issuer (its direct ancestor CA). If no proper has been loaded [`SSLContext.load_verify_locations`](#ssl.SSLContext.load_verify_locations "ssl.SSLContext.load_verify_locations"), validation will fail.
3\.4 新版功能.
`ssl.``VERIFY_CRL_CHECK_CHAIN`Possible value for [`SSLContext.verify_flags`](#ssl.SSLContext.verify_flags "ssl.SSLContext.verify_flags"). In this mode, CRLs of all certificates in the peer cert chain are checked.
3\.4 新版功能.
`ssl.``VERIFY_X509_STRICT`Possible value for [`SSLContext.verify_flags`](#ssl.SSLContext.verify_flags "ssl.SSLContext.verify_flags") to disable workarounds for broken X.509 certificates.
3\.4 新版功能.
`ssl.``VERIFY_X509_TRUSTED_FIRST`Possible value for [`SSLContext.verify_flags`](#ssl.SSLContext.verify_flags "ssl.SSLContext.verify_flags"). It instructs OpenSSL to prefer trusted certificates when building the trust chain to validate a certificate. This flag is enabled by default.
3\.4.4 新版功能.
*class* `ssl.``VerifyFlags`[`enum.IntFlag`](enum.xhtml#enum.IntFlag "enum.IntFlag") collection of VERIFY\_\* constants.
3\.6 新版功能.
`ssl.``PROTOCOL_TLS`Selects the highest protocol version that both the client and server support. Despite the name, this option can select both "SSL" and "TLS" protocols.
3\.6 新版功能.
`ssl.``PROTOCOL_TLS_CLIENT`Auto-negotiate the highest protocol version like [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS"), but only support client-side [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket") connections. The protocol enables [`CERT_REQUIRED`](#ssl.CERT_REQUIRED "ssl.CERT_REQUIRED") and [`check_hostname`](#ssl.SSLContext.check_hostname "ssl.SSLContext.check_hostname") by default.
3\.6 新版功能.
`ssl.``PROTOCOL_TLS_SERVER`Auto-negotiate the highest protocol version like [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS"), but only support server-side [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket") connections.
3\.6 新版功能.
`ssl.``PROTOCOL_SSLv23`Alias for data:PROTOCOL\_TLS.
3\.6 版后已移除: Use [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS") instead.
`ssl.``PROTOCOL_SSLv2`Selects SSL version 2 as the channel encryption protocol.
This protocol is not available if OpenSSL is compiled with the `OPENSSL_NO_SSL2` flag.
警告
SSL version 2 is insecure. Its use is highly discouraged.
3\.6 版后已移除: OpenSSL has removed support for SSLv2.
`ssl.``PROTOCOL_SSLv3`Selects SSL version 3 as the channel encryption protocol.
This protocol is not be available if OpenSSL is compiled with the `OPENSSL_NO_SSLv3` flag.
警告
SSL version 3 is insecure. Its use is highly discouraged.
3\.6 版后已移除: OpenSSL has deprecated all version specific protocols. Use the default protocol [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS") with flags like [`OP_NO_SSLv3`](#ssl.OP_NO_SSLv3 "ssl.OP_NO_SSLv3") instead.
`ssl.``PROTOCOL_TLSv1`Selects TLS version 1.0 as the channel encryption protocol.
3\.6 版后已移除: OpenSSL has deprecated all version specific protocols. Use the default protocol [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS") with flags like [`OP_NO_SSLv3`](#ssl.OP_NO_SSLv3 "ssl.OP_NO_SSLv3") instead.
`ssl.``PROTOCOL_TLSv1_1`Selects TLS version 1.1 as the channel encryption protocol. Available only with openssl version 1.0.1+.
3\.4 新版功能.
3\.6 版后已移除: OpenSSL has deprecated all version specific protocols. Use the default protocol [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS") with flags like [`OP_NO_SSLv3`](#ssl.OP_NO_SSLv3 "ssl.OP_NO_SSLv3") instead.
`ssl.``PROTOCOL_TLSv1_2`Selects TLS version 1.2 as the channel encryption protocol. This is the most modern version, and probably the best choice for maximum protection, if both sides can speak it. Available only with openssl version 1.0.1+.
3\.4 新版功能.
3\.6 版后已移除: OpenSSL has deprecated all version specific protocols. Use the default protocol [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS") with flags like [`OP_NO_SSLv3`](#ssl.OP_NO_SSLv3 "ssl.OP_NO_SSLv3") instead.
`ssl.``OP_ALL`Enables workarounds for various bugs present in other SSL implementations. This option is set by default. It does not necessarily set the same flags as OpenSSL's `SSL_OP_ALL` constant.
3\.2 新版功能.
`ssl.``OP_NO_SSLv2`Prevents an SSLv2 connection. This option is only applicable in conjunction with [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS"). It prevents the peers from choosing SSLv2 as the protocol version.
3\.2 新版功能.
3\.6 版后已移除: SSLv2 is deprecated
`ssl.``OP_NO_SSLv3`Prevents an SSLv3 connection. This option is only applicable in conjunction with [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS"). It prevents the peers from choosing SSLv3 as the protocol version.
3\.2 新版功能.
3\.6 版后已移除: SSLv3 is deprecated
`ssl.``OP_NO_TLSv1`Prevents a TLSv1 connection. This option is only applicable in conjunction with [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS"). It prevents the peers from choosing TLSv1 as the protocol version.
3\.2 新版功能.
3\.7 版后已移除: The option is deprecated since OpenSSL 1.1.0, use the new [`SSLContext.minimum_version`](#ssl.SSLContext.minimum_version "ssl.SSLContext.minimum_version") and [`SSLContext.maximum_version`](#ssl.SSLContext.maximum_version "ssl.SSLContext.maximum_version") instead.
`ssl.``OP_NO_TLSv1_1`Prevents a TLSv1.1 connection. This option is only applicable in conjunction with [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS"). It prevents the peers from choosing TLSv1.1 as the protocol version. Available only with openssl version 1.0.1+.
3\.4 新版功能.
3\.7 版后已移除: The option is deprecated since OpenSSL 1.1.0.
`ssl.``OP_NO_TLSv1_2`Prevents a TLSv1.2 connection. This option is only applicable in conjunction with [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS"). It prevents the peers from choosing TLSv1.2 as the protocol version. Available only with openssl version 1.0.1+.
3\.4 新版功能.
3\.7 版后已移除: The option is deprecated since OpenSSL 1.1.0.
`ssl.``OP_NO_TLSv1_3`Prevents a TLSv1.3 connection. This option is only applicable in conjunction with [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS"). It prevents the peers from choosing TLSv1.3 as the protocol version. TLS 1.3 is available with OpenSSL 1.1.1 or later. When Python has been compiled against an older version of OpenSSL, the flag defaults to .
3\.7 新版功能.
3\.7 版后已移除: The option is deprecated since OpenSSL 1.1.0. It was added to 2.7.15, 3.6.3 and 3.7.0 for backwards compatibility with OpenSSL 1.0.2.
`ssl.``OP_NO_RENEGOTIATION`Disable all renegotiation in TLSv1.2 and earlier. Do not send HelloRequest messages, and ignore renegotiation requests via ClientHello.
This option is only available with OpenSSL 1.1.0h and later.
3\.7 新版功能.
`ssl.``OP_CIPHER_SERVER_PREFERENCE`Use the server's cipher ordering preference, rather than the client's. This option has no effect on client sockets and SSLv2 server sockets.
3\.3 新版功能.
`ssl.``OP_SINGLE_DH_USE`Prevents re-use of the same DH key for distinct SSL sessions. This improves forward secrecy but requires more computational resources. This option only applies to server sockets.
3\.3 新版功能.
`ssl.``OP_SINGLE_ECDH_USE`Prevents re-use of the same ECDH key for distinct SSL sessions. This improves forward secrecy but requires more computational resources. This option only applies to server sockets.
3\.3 新版功能.
`ssl.``OP_ENABLE_MIDDLEBOX_COMPAT`Send dummy Change Cipher Spec (CCS) messages in TLS 1.3 handshake to make a TLS 1.3 connection look more like a TLS 1.2 connection.
This option is only available with OpenSSL 1.1.1 and later.
3\.8 新版功能.
`ssl.``OP_NO_COMPRESSION`Disable compression on the SSL channel. This is useful if the application protocol supports its own compression scheme.
This option is only available with OpenSSL 1.0.0 and later.
3\.3 新版功能.
*class* `ssl.``Options`[`enum.IntFlag`](enum.xhtml#enum.IntFlag "enum.IntFlag") collection of OP\_\* constants.
`ssl.``OP_NO_TICKET`Prevent client side from requesting a session ticket.
3\.6 新版功能.
`ssl.``HAS_ALPN`Whether the OpenSSL library has built-in support for the *Application-Layer Protocol Negotiation* TLS extension as described in [**RFC 7301**](https://tools.ietf.org/html/rfc7301.html) \[https://tools.ietf.org/html/rfc7301.html\].
3\.5 新版功能.
`ssl.``HAS_NEVER_CHECK_COMMON_NAME`Whether the OpenSSL library has built-in support not checking subject common name and [`SSLContext.hostname_checks_common_name`](#ssl.SSLContext.hostname_checks_common_name "ssl.SSLContext.hostname_checks_common_name") is writeable.
3\.7 新版功能.
`ssl.``HAS_ECDH`Whether the OpenSSL library has built-in support for the Elliptic Curve-based Diffie-Hellman key exchange. This should be true unless the feature was explicitly disabled by the distributor.
3\.3 新版功能.
`ssl.``HAS_SNI`Whether the OpenSSL library has built-in support for the *Server Name Indication* extension (as defined in [**RFC 6066**](https://tools.ietf.org/html/rfc6066.html) \[https://tools.ietf.org/html/rfc6066.html\]).
3\.2 新版功能.
`ssl.``HAS_NPN`Whether the OpenSSL library has built-in support for the *Next Protocol Negotiation* as described in the [Application Layer Protocol Negotiation](https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation) \[https://en.wikipedia.org/wiki/Application-Layer\_Protocol\_Negotiation\]. When true, you can use the [`SSLContext.set_npn_protocols()`](#ssl.SSLContext.set_npn_protocols "ssl.SSLContext.set_npn_protocols") method to advertise which protocols you want to support.
3\.3 新版功能.
`ssl.``HAS_SSLv2`Whether the OpenSSL library has built-in support for the SSL 2.0 protocol.
3\.7 新版功能.
`ssl.``HAS_SSLv3`Whether the OpenSSL library has built-in support for the SSL 3.0 protocol.
3\.7 新版功能.
`ssl.``HAS_TLSv1`Whether the OpenSSL library has built-in support for the TLS 1.0 protocol.
3\.7 新版功能.
`ssl.``HAS_TLSv1_1`Whether the OpenSSL library has built-in support for the TLS 1.1 protocol.
3\.7 新版功能.
`ssl.``HAS_TLSv1_2`Whether the OpenSSL library has built-in support for the TLS 1.2 protocol.
3\.7 新版功能.
`ssl.``HAS_TLSv1_3`Whether the OpenSSL library has built-in support for the TLS 1.3 protocol.
3\.7 新版功能.
`ssl.``CHANNEL_BINDING_TYPES`List of supported TLS channel binding types. Strings in this list can be used as arguments to [`SSLSocket.get_channel_binding()`](#ssl.SSLSocket.get_channel_binding "ssl.SSLSocket.get_channel_binding").
3\.3 新版功能.
`ssl.``OPENSSL_VERSION`The version string of the OpenSSL library loaded by the interpreter:
```
>>> ssl.OPENSSL_VERSION
'OpenSSL 1.0.2k 26 Jan 2017'
```
3\.2 新版功能.
`ssl.``OPENSSL_VERSION_INFO`A tuple of five integers representing version information about the OpenSSL library:
```
>>> ssl.OPENSSL_VERSION_INFO
(1, 0, 2, 11, 15)
```
3\.2 新版功能.
`ssl.``OPENSSL_VERSION_NUMBER`The raw version number of the OpenSSL library, as a single integer:
```
>>> ssl.OPENSSL_VERSION_NUMBER
268443839
>>> hex(ssl.OPENSSL_VERSION_NUMBER)
'0x100020bf'
```
3\.2 新版功能.
`ssl.``ALERT_DESCRIPTION_HANDSHAKE_FAILURE``ssl.``ALERT_DESCRIPTION_INTERNAL_ERROR``ALERT_DESCRIPTION_*`Alert Descriptions from [**RFC 5246**](https://tools.ietf.org/html/rfc5246.html) \[https://tools.ietf.org/html/rfc5246.html\] and others. The [IANA TLS Alert Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6) \[https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6\]contains this list and references to the RFCs where their meaning is defined.
Used as the return value of the callback function in [`SSLContext.set_servername_callback()`](#ssl.SSLContext.set_servername_callback "ssl.SSLContext.set_servername_callback").
3\.4 新版功能.
*class* `ssl.``AlertDescription`[`enum.IntEnum`](enum.xhtml#enum.IntEnum "enum.IntEnum") collection of ALERT\_DESCRIPTION\_\* constants.
3\.6 新版功能.
`Purpose.``SERVER_AUTH`Option for [`create_default_context()`](#ssl.create_default_context "ssl.create_default_context") and [`SSLContext.load_default_certs()`](#ssl.SSLContext.load_default_certs "ssl.SSLContext.load_default_certs"). This value indicates that the context may be used to authenticate Web servers (therefore, it will be used to create client-side sockets).
3\.4 新版功能.
`Purpose.``CLIENT_AUTH`Option for [`create_default_context()`](#ssl.create_default_context "ssl.create_default_context") and [`SSLContext.load_default_certs()`](#ssl.SSLContext.load_default_certs "ssl.SSLContext.load_default_certs"). This value indicates that the context may be used to authenticate Web clients (therefore, it will be used to create server-side sockets).
3\.4 新版功能.
*class* `ssl.``SSLErrorNumber`[`enum.IntEnum`](enum.xhtml#enum.IntEnum "enum.IntEnum") collection of SSL\_ERROR\_\* constants.
3\.6 新版功能.
*class* `ssl.``TLSVersion`[`enum.IntEnum`](enum.xhtml#enum.IntEnum "enum.IntEnum") collection of SSL and TLS versions for [`SSLContext.maximum_version`](#ssl.SSLContext.maximum_version "ssl.SSLContext.maximum_version") and [`SSLContext.minimum_version`](#ssl.SSLContext.minimum_version "ssl.SSLContext.minimum_version").
3\.7 新版功能.
`TLSVersion.``MINIMUM_SUPPORTED``TLSVersion.``MAXIMUM_SUPPORTED`The minimum or maximum supported SSL or TLS version. These are magic constants. Their values don't reflect the lowest and highest available TLS/SSL versions.
`TLSVersion.``SSLv3``TLSVersion.``TLSv1``TLSVersion.``TLSv1_1``TLSVersion.``TLSv1_2``TLSVersion.``TLSv1_3`SSL 3.0 to TLS 1.3.
## SSL Sockets
*class* `ssl.``SSLSocket`(*socket.socket*)SSL sockets provide the following methods of [Socket Objects](socket.xhtml#socket-objects):
- [`accept()`](socket.xhtml#socket.socket.accept "socket.socket.accept")
- [`bind()`](socket.xhtml#socket.socket.bind "socket.socket.bind")
- [`close()`](socket.xhtml#socket.socket.close "socket.socket.close")
- [`connect()`](socket.xhtml#socket.socket.connect "socket.socket.connect")
- [`detach()`](socket.xhtml#socket.socket.detach "socket.socket.detach")
- [`fileno()`](socket.xhtml#socket.socket.fileno "socket.socket.fileno")
- [`getpeername()`](socket.xhtml#socket.socket.getpeername "socket.socket.getpeername"), [`getsockname()`](socket.xhtml#socket.socket.getsockname "socket.socket.getsockname")
- [`getsockopt()`](socket.xhtml#socket.socket.getsockopt "socket.socket.getsockopt"), [`setsockopt()`](socket.xhtml#socket.socket.setsockopt "socket.socket.setsockopt")
- [`gettimeout()`](socket.xhtml#socket.socket.gettimeout "socket.socket.gettimeout"), [`settimeout()`](socket.xhtml#socket.socket.settimeout "socket.socket.settimeout"), [`setblocking()`](socket.xhtml#socket.socket.setblocking "socket.socket.setblocking")
- [`listen()`](socket.xhtml#socket.socket.listen "socket.socket.listen")
- [`makefile()`](socket.xhtml#socket.socket.makefile "socket.socket.makefile")
- [`recv()`](socket.xhtml#socket.socket.recv "socket.socket.recv"), [`recv_into()`](socket.xhtml#socket.socket.recv_into "socket.socket.recv_into")(but passing a non-zero `flags` argument is not allowed)
- [`send()`](socket.xhtml#socket.socket.send "socket.socket.send"), [`sendall()`](socket.xhtml#socket.socket.sendall "socket.socket.sendall") (with the same limitation)
- [`sendfile()`](socket.xhtml#socket.socket.sendfile "socket.socket.sendfile") (but [`os.sendfile`](os.xhtml#os.sendfile "os.sendfile") will be used for plain-text sockets only, else [`send()`](socket.xhtml#socket.socket.send "socket.socket.send") will be used)
- [`shutdown()`](socket.xhtml#socket.socket.shutdown "socket.socket.shutdown")
However, since the SSL (and TLS) protocol has its own framing atop of TCP, the SSL sockets abstraction can, in certain respects, diverge from the specification of normal, OS-level sockets. See especially the [notes on non-blocking sockets](#ssl-nonblocking).
Instances of [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket") must be created using the [`SSLContext.wrap_socket()`](#ssl.SSLContext.wrap_socket "ssl.SSLContext.wrap_socket") method.
在 3.5 版更改: The `sendfile()` method was added.
在 3.5 版更改: The `shutdown()` does not reset the socket timeout each time bytes are received or sent. The socket timeout is now to maximum total duration of the shutdown.
3\.6 版后已移除: It is deprecated to create a [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket") instance directly, use [`SSLContext.wrap_socket()`](#ssl.SSLContext.wrap_socket "ssl.SSLContext.wrap_socket") to wrap a socket.
在 3.7 版更改: [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket") instances must to created with [`wrap_socket()`](#ssl.SSLContext.wrap_socket "ssl.SSLContext.wrap_socket"). In earlier versions, it was possible to create instances directly. This was never documented or officially supported.
SSL sockets also have the following additional methods and attributes:
`SSLSocket.``read`(*len=1024*, *buffer=None*)Read up to *len* bytes of data from the SSL socket and return the result as a `bytes` instance. If *buffer* is specified, then read into the buffer instead, and return the number of bytes read.
Raise [`SSLWantReadError`](#ssl.SSLWantReadError "ssl.SSLWantReadError") or [`SSLWantWriteError`](#ssl.SSLWantWriteError "ssl.SSLWantWriteError") if the socket is [non-blocking](#ssl-nonblocking) and the read would block.
As at any time a re-negotiation is possible, a call to [`read()`](#ssl.SSLSocket.read "ssl.SSLSocket.read") can also cause write operations.
在 3.5 版更改: The socket timeout is no more reset each time bytes are received or sent. The socket timeout is now to maximum total duration to read up to *len*bytes.
3\.6 版后已移除: Use `recv()` instead of [`read()`](#ssl.SSLSocket.read "ssl.SSLSocket.read").
`SSLSocket.``write`(*buf*)Write *buf* to the SSL socket and return the number of bytes written. The *buf* argument must be an object supporting the buffer interface.
Raise [`SSLWantReadError`](#ssl.SSLWantReadError "ssl.SSLWantReadError") or [`SSLWantWriteError`](#ssl.SSLWantWriteError "ssl.SSLWantWriteError") if the socket is [non-blocking](#ssl-nonblocking) and the write would block.
As at any time a re-negotiation is possible, a call to [`write()`](#ssl.SSLSocket.write "ssl.SSLSocket.write") can also cause read operations.
在 3.5 版更改: The socket timeout is no more reset each time bytes are received or sent. The socket timeout is now to maximum total duration to write *buf*.
3\.6 版后已移除: Use `send()` instead of [`write()`](#ssl.SSLSocket.write "ssl.SSLSocket.write").
注解
The [`read()`](#ssl.SSLSocket.read "ssl.SSLSocket.read") and [`write()`](#ssl.SSLSocket.write "ssl.SSLSocket.write") methods are the low-level methods that read and write unencrypted, application-level data and decrypt/encrypt it to encrypted, wire-level data. These methods require an active SSL connection, i.e. the handshake was completed and [`SSLSocket.unwrap()`](#ssl.SSLSocket.unwrap "ssl.SSLSocket.unwrap") was not called.
Normally you should use the socket API methods like [`recv()`](socket.xhtml#socket.socket.recv "socket.socket.recv") and [`send()`](socket.xhtml#socket.socket.send "socket.socket.send") instead of these methods.
`SSLSocket.``do_handshake`()Perform the SSL setup handshake.
在 3.4 版更改: The handshake method also performs [`match_hostname()`](#ssl.match_hostname "ssl.match_hostname") when the [`check_hostname`](#ssl.SSLContext.check_hostname "ssl.SSLContext.check_hostname") attribute of the socket's [`context`](#ssl.SSLSocket.context "ssl.SSLSocket.context") is true.
在 3.5 版更改: The socket timeout is no more reset each time bytes are received or sent. The socket timeout is now to maximum total duration of the handshake.
在 3.7 版更改: Hostname or IP address is matched by OpenSSL during handshake. The function [`match_hostname()`](#ssl.match_hostname "ssl.match_hostname") is no longer used. In case OpenSSL refuses a hostname or IP address, the handshake is aborted early and a TLS alert message is send to the peer.
`SSLSocket.``getpeercert`(*binary\_form=False*)If there is no certificate for the peer on the other end of the connection, return `None`. If the SSL handshake hasn't been done yet, raise [`ValueError`](exceptions.xhtml#ValueError "ValueError").
If the `binary_form` parameter is [`False`](constants.xhtml#False "False"), and a certificate was received from the peer, this method returns a [`dict`](stdtypes.xhtml#dict "dict") instance. If the certificate was not validated, the dict is empty. If the certificate was validated, it returns a dict with several keys, amongst them `subject`(the principal for which the certificate was issued) and `issuer`(the principal issuing the certificate). If a certificate contains an instance of the *Subject Alternative Name* extension (see [**RFC 3280**](https://tools.ietf.org/html/rfc3280.html) \[https://tools.ietf.org/html/rfc3280.html\]), there will also be a `subjectAltName` key in the dictionary.
The `subject` and `issuer` fields are tuples containing the sequence of relative distinguished names (RDNs) given in the certificate's data structure for the respective fields, and each RDN is a sequence of name-value pairs. Here is a real-world example:
```
{'issuer': ((('countryName', 'IL'),),
(('organizationName', 'StartCom Ltd.'),),
(('organizationalUnitName',
'Secure Digital Certificate Signing'),),
(('commonName',
'StartCom Class 2 Primary Intermediate Server CA'),)),
'notAfter': 'Nov 22 08:15:19 2013 GMT',
'notBefore': 'Nov 21 03:09:52 2011 GMT',
'serialNumber': '95F0',
'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),
(('countryName', 'US'),),
(('stateOrProvinceName', 'California'),),
(('localityName', 'San Francisco'),),
(('organizationName', 'Electronic Frontier Foundation, Inc.'),),
(('commonName', '*.eff.org'),),
(('emailAddress', 'hostmaster@eff.org'),)),
'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
'version': 3}
```
注解
To validate a certificate for a particular service, you can use the [`match_hostname()`](#ssl.match_hostname "ssl.match_hostname") function.
If the `binary_form` parameter is [`True`](constants.xhtml#True "True"), and a certificate was provided, this method returns the DER-encoded form of the entire certificate as a sequence of bytes, or [`None`](constants.xhtml#None "None") if the peer did not provide a certificate. Whether the peer provides a certificate depends on the SSL socket's role:
- for a client SSL socket, the server will always provide a certificate, regardless of whether validation was required;
- for a server SSL socket, the client will only provide a certificate when requested by the server; therefore [`getpeercert()`](#ssl.SSLSocket.getpeercert "ssl.SSLSocket.getpeercert") will return [`None`](constants.xhtml#None "None") if you used [`CERT_NONE`](#ssl.CERT_NONE "ssl.CERT_NONE") (rather than [`CERT_OPTIONAL`](#ssl.CERT_OPTIONAL "ssl.CERT_OPTIONAL") or [`CERT_REQUIRED`](#ssl.CERT_REQUIRED "ssl.CERT_REQUIRED")).
在 3.2 版更改: The returned dictionary includes additional items such as `issuer`and `notBefore`.
在 3.4 版更改: [`ValueError`](exceptions.xhtml#ValueError "ValueError") is raised when the handshake isn't done. The returned dictionary includes additional X509v3 extension items such as `crlDistributionPoints`, `caIssuers` and `OCSP` URIs.
`SSLSocket.``cipher`()Returns a three-value tuple containing the name of the cipher being used, the version of the SSL protocol that defines its use, and the number of secret bits being used. If no connection has been established, returns `None`.
`SSLSocket.``shared_ciphers`()Return the list of ciphers shared by the client during the handshake. Each entry of the returned list is a three-value tuple containing the name of the cipher, the version of the SSL protocol that defines its use, and the number of secret bits the cipher uses. [`shared_ciphers()`](#ssl.SSLSocket.shared_ciphers "ssl.SSLSocket.shared_ciphers") returns `None` if no connection has been established or the socket is a client socket.
3\.5 新版功能.
`SSLSocket.``compression`()Return the compression algorithm being used as a string, or `None`if the connection isn't compressed.
If the higher-level protocol supports its own compression mechanism, you can use [`OP_NO_COMPRESSION`](#ssl.OP_NO_COMPRESSION "ssl.OP_NO_COMPRESSION") to disable SSL-level compression.
3\.3 新版功能.
`SSLSocket.``get_channel_binding`(*cb\_type="tls-unique"*)Get channel binding data for current connection, as a bytes object. Returns `None` if not connected or the handshake has not been completed.
The *cb\_type* parameter allow selection of the desired channel binding type. Valid channel binding types are listed in the [`CHANNEL_BINDING_TYPES`](#ssl.CHANNEL_BINDING_TYPES "ssl.CHANNEL_BINDING_TYPES") list. Currently only the 'tls-unique' channel binding, defined by [**RFC 5929**](https://tools.ietf.org/html/rfc5929.html) \[https://tools.ietf.org/html/rfc5929.html\], is supported. [`ValueError`](exceptions.xhtml#ValueError "ValueError") will be raised if an unsupported channel binding type is requested.
3\.3 新版功能.
`SSLSocket.``selected_alpn_protocol`()Return the protocol that was selected during the TLS handshake. If [`SSLContext.set_alpn_protocols()`](#ssl.SSLContext.set_alpn_protocols "ssl.SSLContext.set_alpn_protocols") was not called, if the other party does not support ALPN, if this socket does not support any of the client's proposed protocols, or if the handshake has not happened yet, `None` is returned.
3\.5 新版功能.
`SSLSocket.``selected_npn_protocol`()Return the higher-level protocol that was selected during the TLS/SSL handshake. If [`SSLContext.set_npn_protocols()`](#ssl.SSLContext.set_npn_protocols "ssl.SSLContext.set_npn_protocols") was not called, or if the other party does not support NPN, or if the handshake has not yet happened, this will return `None`.
3\.3 新版功能.
`SSLSocket.``unwrap`()Performs the SSL shutdown handshake, which removes the TLS layer from the underlying socket, and returns the underlying socket object. This can be used to go from encrypted operation over a connection to unencrypted. The returned socket should always be used for further communication with the other side of the connection, rather than the original socket.
`SSLSocket.``verify_client_post_handshake`()Requests post-handshake authentication (PHA) from a TLS 1.3 client. PHA can only be initiated for a TLS 1.3 connection from a server-side socket, after the initial TLS handshake and with PHA enabled on both sides, see [`SSLContext.post_handshake_auth`](#ssl.SSLContext.post_handshake_auth "ssl.SSLContext.post_handshake_auth").
The method does not perform a cert exchange immediately. The server-side sends a CertificateRequest during the next write event and expects the client to respond with a certificate on the next read event.
If any precondition isn't met (e.g. not TLS 1.3, PHA not enabled), an [`SSLError`](#ssl.SSLError "ssl.SSLError") is raised.
注解
Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 support, the method raises [`NotImplementedError`](exceptions.xhtml#NotImplementedError "NotImplementedError").
3\.7.1 新版功能.
`SSLSocket.``version`()Return the actual SSL protocol version negotiated by the connection as a string, or `None` is no secure connection is established. As of this writing, possible return values include `"SSLv2"`, `"SSLv3"`, `"TLSv1"`, `"TLSv1.1"` and `"TLSv1.2"`. Recent OpenSSL versions may define more return values.
3\.5 新版功能.
`SSLSocket.``pending`()Returns the number of already decrypted bytes available for read, pending on the connection.
`SSLSocket.``context`The [`SSLContext`](#ssl.SSLContext "ssl.SSLContext") object this SSL socket is tied to. If the SSL socket was created using the deprecated [`wrap_socket()`](#ssl.wrap_socket "ssl.wrap_socket") function (rather than [`SSLContext.wrap_socket()`](#ssl.SSLContext.wrap_socket "ssl.SSLContext.wrap_socket")), this is a custom context object created for this SSL socket.
3\.2 新版功能.
`SSLSocket.``server_side`A boolean which is `True` for server-side sockets and `False` for client-side sockets.
3\.2 新版功能.
`SSLSocket.``server_hostname`Hostname of the server: [`str`](stdtypes.xhtml#str "str") type, or `None` for server-side socket or if the hostname was not specified in the constructor.
3\.2 新版功能.
在 3.7 版更改: The attribute is now always ASCII text. When `server_hostname` is an internationalized domain name (IDN), this attribute now stores the A-label form (`"xn--pythn-mua.org"`), rather than the U-label form (`"pythön.org"`).
`SSLSocket.``session`The [`SSLSession`](#ssl.SSLSession "ssl.SSLSession") for this SSL connection. The session is available for client and server side sockets after the TLS handshake has been performed. For client sockets the session can be set before [`do_handshake()`](#ssl.SSLSocket.do_handshake "ssl.SSLSocket.do_handshake") has been called to reuse a session.
3\.6 新版功能.
`SSLSocket.``session_reused`3\.6 新版功能.
## SSL Contexts
3\.2 新版功能.
An SSL context holds various data longer-lived than single SSL connections, such as SSL configuration options, certificate(s) and private key(s). It also manages a cache of SSL sessions for server-side sockets, in order to speed up repeated connections from the same clients.
*class* `ssl.``SSLContext`(*protocol=PROTOCOL\_TLS*)Create a new SSL context. You may pass *protocol* which must be one of the `PROTOCOL_*` constants defined in this module. The parameter specifies which version of the SSL protocol to use. Typically, the server chooses a particular protocol version, and the client must adapt to the server's choice. Most of the versions are not interoperable with the other versions. If not specified, the default is [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS"); it provides the most compatibility with other versions.
Here's a table showing which versions in a client (down the side) can connect to which versions in a server (along the top):
> *client* / **server**
>
> **SSLv2**
>
> **SSLv3**
>
> **TLS** [3](#id9)
>
> **TLSv1**
>
> **TLSv1.1**
>
> **TLSv1.2**
>
> *SSLv2*
>
> yes
>
> no
>
> no [1](#id7)
>
> no
>
> no
>
> no
>
> *SSLv3*
>
> no
>
> yes
>
> no [2](#id8)
>
> no
>
> no
>
> no
>
> *TLS* (*SSLv23*) [3](#id9)
>
> no [1](#id7)
>
> no [2](#id8)
>
> yes
>
> yes
>
> yes
>
> yes
>
> *TLSv1*
>
> no
>
> no
>
> yes
>
> yes
>
> no
>
> no
>
> *TLSv1.1*
>
> no
>
> no
>
> yes
>
> no
>
> yes
>
> no
>
> *TLSv1.2*
>
> no
>
> no
>
> yes
>
> no
>
> no
>
> yes
脚注
1([1](#id2),[2](#id5))[`SSLContext`](#ssl.SSLContext "ssl.SSLContext") disables SSLv2 with [`OP_NO_SSLv2`](#ssl.OP_NO_SSLv2 "ssl.OP_NO_SSLv2") by default.
2([1](#id3),[2](#id6))[`SSLContext`](#ssl.SSLContext "ssl.SSLContext") disables SSLv3 with [`OP_NO_SSLv3`](#ssl.OP_NO_SSLv3 "ssl.OP_NO_SSLv3") by default.
3([1](#id1),[2](#id4))TLS 1.3 protocol will be available with [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS") in OpenSSL >= 1.1.1. There is no dedicated PROTOCOL constant for just TLS 1.3.
参见
[`create_default_context()`](#ssl.create_default_context "ssl.create_default_context") lets the [`ssl`](#module-ssl "ssl: TLS/SSL wrapper for socket objects") module choose security settings for a given purpose.
在 3.6 版更改: The context is created with secure default values. The options [`OP_NO_COMPRESSION`](#ssl.OP_NO_COMPRESSION "ssl.OP_NO_COMPRESSION"), [`OP_CIPHER_SERVER_PREFERENCE`](#ssl.OP_CIPHER_SERVER_PREFERENCE "ssl.OP_CIPHER_SERVER_PREFERENCE"), [`OP_SINGLE_DH_USE`](#ssl.OP_SINGLE_DH_USE "ssl.OP_SINGLE_DH_USE"), [`OP_SINGLE_ECDH_USE`](#ssl.OP_SINGLE_ECDH_USE "ssl.OP_SINGLE_ECDH_USE"), [`OP_NO_SSLv2`](#ssl.OP_NO_SSLv2 "ssl.OP_NO_SSLv2") (except for [`PROTOCOL_SSLv2`](#ssl.PROTOCOL_SSLv2 "ssl.PROTOCOL_SSLv2")), and [`OP_NO_SSLv3`](#ssl.OP_NO_SSLv3 "ssl.OP_NO_SSLv3") (except for [`PROTOCOL_SSLv3`](#ssl.PROTOCOL_SSLv3 "ssl.PROTOCOL_SSLv3")) are set by default. The initial cipher suite list contains only `HIGH`ciphers, no `NULL` ciphers and no `MD5` ciphers (except for [`PROTOCOL_SSLv2`](#ssl.PROTOCOL_SSLv2 "ssl.PROTOCOL_SSLv2")).
[`SSLContext`](#ssl.SSLContext "ssl.SSLContext") objects have the following methods and attributes:
`SSLContext.``cert_store_stats`()Get statistics about quantities of loaded X.509 certificates, count of X.509 certificates flagged as CA certificates and certificate revocation lists as dictionary.
Example for a context with one CA cert and one other cert:
```
>>> context.cert_store_stats()
{'crl': 0, 'x509_ca': 1, 'x509': 2}
```
3\.4 新版功能.
`SSLContext.``load_cert_chain`(*certfile*, *keyfile=None*, *password=None*)Load a private key and the corresponding certificate. The *certfile*string must be the path to a single file in PEM format containing the certificate as well as any number of CA certificates needed to establish the certificate's authenticity. The *keyfile* string, if present, must point to a file containing the private key in. Otherwise the private key will be taken from *certfile* as well. See the discussion of [Certificates](#ssl-certificates) for more information on how the certificate is stored in the *certfile*.
The *password* argument may be a function to call to get the password for decrypting the private key. It will only be called if the private key is encrypted and a password is necessary. It will be called with no arguments, and it should return a string, bytes, or bytearray. If the return value is a string it will be encoded as UTF-8 before using it to decrypt the key. Alternatively a string, bytes, or bytearray value may be supplied directly as the *password* argument. It will be ignored if the private key is not encrypted and no password is needed.
If the *password* argument is not specified and a password is required, OpenSSL's built-in password prompting mechanism will be used to interactively prompt the user for a password.
An [`SSLError`](#ssl.SSLError "ssl.SSLError") is raised if the private key doesn't match with the certificate.
在 3.3 版更改: New optional argument *password*.
`SSLContext.``load_default_certs`(*purpose=Purpose.SERVER\_AUTH*)Load a set of default "certification authority" (CA) certificates from default locations. On Windows it loads CA certs from the `CA` and `ROOT` system stores. On other systems it calls [`SSLContext.set_default_verify_paths()`](#ssl.SSLContext.set_default_verify_paths "ssl.SSLContext.set_default_verify_paths"). In the future the method may load CA certificates from other locations, too.
The *purpose* flag specifies what kind of CA certificates are loaded. The default settings [`Purpose.SERVER_AUTH`](#ssl.Purpose.SERVER_AUTH "ssl.Purpose.SERVER_AUTH") loads certificates, that are flagged and trusted for TLS web server authentication (client side sockets). [`Purpose.CLIENT_AUTH`](#ssl.Purpose.CLIENT_AUTH "ssl.Purpose.CLIENT_AUTH") loads CA certificates for client certificate verification on the server side.
3\.4 新版功能.
`SSLContext.``load_verify_locations`(*cafile=None*, *capath=None*, *cadata=None*)Load a set of "certification authority" (CA) certificates used to validate other peers' certificates when [`verify_mode`](#ssl.SSLContext.verify_mode "ssl.SSLContext.verify_mode") is other than [`CERT_NONE`](#ssl.CERT_NONE "ssl.CERT_NONE"). At least one of *cafile* or *capath* must be specified.
This method can also load certification revocation lists (CRLs) in PEM or DER format. In order to make use of CRLs, [`SSLContext.verify_flags`](#ssl.SSLContext.verify_flags "ssl.SSLContext.verify_flags")must be configured properly.
The *cafile* string, if present, is the path to a file of concatenated CA certificates in PEM format. See the discussion of [Certificates](#ssl-certificates) for more information about how to arrange the certificates in this file.
The *capath* string, if present, is the path to a directory containing several CA certificates in PEM format, following an [OpenSSL specific layout](https://www.openssl.org/docs/manmaster/man3/SSL_CTX_load_verify_locations.html) \[https://www.openssl.org/docs/manmaster/man3/SSL\_CTX\_load\_verify\_locations.html\].
The *cadata* object, if present, is either an ASCII string of one or more PEM-encoded certificates or a [bytes-like object](../glossary.xhtml#term-bytes-like-object) of DER-encoded certificates. Like with *capath* extra lines around PEM-encoded certificates are ignored but at least one certificate must be present.
在 3.4 版更改: New optional argument *cadata*
`SSLContext.``get_ca_certs`(*binary\_form=False*)Get a list of loaded "certification authority" (CA) certificates. If the `binary_form` parameter is [`False`](constants.xhtml#False "False") each list entry is a dict like the output of [`SSLSocket.getpeercert()`](#ssl.SSLSocket.getpeercert "ssl.SSLSocket.getpeercert"). Otherwise the method returns a list of DER-encoded certificates. The returned list does not contain certificates from *capath* unless a certificate was requested and loaded by a SSL connection.
注解
Certificates in a capath directory aren't loaded unless they have been used at least once.
3\.4 新版功能.
`SSLContext.``get_ciphers`()Get a list of enabled ciphers. The list is in order of cipher priority. See [`SSLContext.set_ciphers()`](#ssl.SSLContext.set_ciphers "ssl.SSLContext.set_ciphers").
示例:
```
>>> ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
>>> ctx.set_ciphers('ECDHE+AESGCM:!ECDSA')
>>> ctx.get_ciphers() # OpenSSL 1.0.x
[{'alg_bits': 256,
'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA '
'Enc=AESGCM(256) Mac=AEAD',
'id': 50380848,
'name': 'ECDHE-RSA-AES256-GCM-SHA384',
'protocol': 'TLSv1/SSLv3',
'strength_bits': 256},
{'alg_bits': 128,
'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA '
'Enc=AESGCM(128) Mac=AEAD',
'id': 50380847,
'name': 'ECDHE-RSA-AES128-GCM-SHA256',
'protocol': 'TLSv1/SSLv3',
'strength_bits': 128}]
```
On OpenSSL 1.1 and newer the cipher dict contains additional fields:
```
>>> ctx.get_ciphers() # OpenSSL 1.1+
[{'aead': True,
'alg_bits': 256,
'auth': 'auth-rsa',
'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA '
'Enc=AESGCM(256) Mac=AEAD',
'digest': None,
'id': 50380848,
'kea': 'kx-ecdhe',
'name': 'ECDHE-RSA-AES256-GCM-SHA384',
'protocol': 'TLSv1.2',
'strength_bits': 256,
'symmetric': 'aes-256-gcm'},
{'aead': True,
'alg_bits': 128,
'auth': 'auth-rsa',
'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA '
'Enc=AESGCM(128) Mac=AEAD',
'digest': None,
'id': 50380847,
'kea': 'kx-ecdhe',
'name': 'ECDHE-RSA-AES128-GCM-SHA256',
'protocol': 'TLSv1.2',
'strength_bits': 128,
'symmetric': 'aes-128-gcm'}]
```
[Availability](intro.xhtml#availability): OpenSSL 1.0.2+.
3\.6 新版功能.
`SSLContext.``set_default_verify_paths`()Load a set of default "certification authority" (CA) certificates from a filesystem path defined when building the OpenSSL library. Unfortunately, there's no easy way to know whether this method succeeds: no error is returned if no certificates are to be found. When the OpenSSL library is provided as part of the operating system, though, it is likely to be configured properly.
`SSLContext.``set_ciphers`(*ciphers*)Set the available ciphers for sockets created with this context. It should be a string in the [OpenSSL cipher list format](https://www.openssl.org/docs/manmaster/man1/ciphers.html) \[https://www.openssl.org/docs/manmaster/man1/ciphers.html\]. If no cipher can be selected (because compile-time options or other configuration forbids use of all the specified ciphers), an [`SSLError`](#ssl.SSLError "ssl.SSLError") will be raised.
注解
when connected, the [`SSLSocket.cipher()`](#ssl.SSLSocket.cipher "ssl.SSLSocket.cipher") method of SSL sockets will give the currently selected cipher.
OpenSSL 1.1.1 has TLS 1.3 cipher suites enabled by default. The suites cannot be disabled with [`set_ciphers()`](#ssl.SSLContext.set_ciphers "ssl.SSLContext.set_ciphers").
`SSLContext.``set_alpn_protocols`(*protocols*)Specify which protocols the socket should advertise during the SSL/TLS handshake. It should be a list of ASCII strings, like
```
['http/1.1',
'spdy/2']
```
, ordered by preference. The selection of a protocol will happen during the handshake, and will play out according to [**RFC 7301**](https://tools.ietf.org/html/rfc7301.html) \[https://tools.ietf.org/html/rfc7301.html\]. After a successful handshake, the [`SSLSocket.selected_alpn_protocol()`](#ssl.SSLSocket.selected_alpn_protocol "ssl.SSLSocket.selected_alpn_protocol") method will return the agreed-upon protocol.
This method will raise [`NotImplementedError`](exceptions.xhtml#NotImplementedError "NotImplementedError") if [`HAS_ALPN`](#ssl.HAS_ALPN "ssl.HAS_ALPN") is False.
OpenSSL 1.1.0 to 1.1.0e will abort the handshake and raise [`SSLError`](#ssl.SSLError "ssl.SSLError")when both sides support ALPN but cannot agree on a protocol. 1.1.0f+ behaves like 1.0.2, [`SSLSocket.selected_alpn_protocol()`](#ssl.SSLSocket.selected_alpn_protocol "ssl.SSLSocket.selected_alpn_protocol") returns None.
3\.5 新版功能.
`SSLContext.``set_npn_protocols`(*protocols*)Specify which protocols the socket should advertise during the SSL/TLS handshake. It should be a list of strings, like `['http/1.1', 'spdy/2']`, ordered by preference. The selection of a protocol will happen during the handshake, and will play out according to the [Application Layer Protocol Negotiation](https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation) \[https://en.wikipedia.org/wiki/Application-Layer\_Protocol\_Negotiation\]. After a successful handshake, the [`SSLSocket.selected_npn_protocol()`](#ssl.SSLSocket.selected_npn_protocol "ssl.SSLSocket.selected_npn_protocol") method will return the agreed-upon protocol.
This method will raise [`NotImplementedError`](exceptions.xhtml#NotImplementedError "NotImplementedError") if [`HAS_NPN`](#ssl.HAS_NPN "ssl.HAS_NPN") is False.
3\.3 新版功能.
`SSLContext.``sni_callback`Register a callback function that will be called after the TLS Client Hello handshake message has been received by the SSL/TLS server when the TLS client specifies a server name indication. The server name indication mechanism is specified in [**RFC 6066**](https://tools.ietf.org/html/rfc6066.html) \[https://tools.ietf.org/html/rfc6066.html\] section 3 - Server Name Indication.
Only one callback can be set per `SSLContext`. If *sni\_callback*is set to `None` then the callback is disabled. Calling this function a subsequent time will disable the previously registered callback.
The callback function will be called with three arguments; the first being the [`ssl.SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket"), the second is a string that represents the server name that the client is intending to communicate (or [`None`](constants.xhtml#None "None") if the TLS Client Hello does not contain a server name) and the third argument is the original [`SSLContext`](#ssl.SSLContext "ssl.SSLContext"). The server name argument is text. For internationalized domain name, the server name is an IDN A-label (`"xn--pythn-mua.org"`).
A typical use of this callback is to change the [`ssl.SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket")'s [`SSLSocket.context`](#ssl.SSLSocket.context "ssl.SSLSocket.context") attribute to a new object of type [`SSLContext`](#ssl.SSLContext "ssl.SSLContext") representing a certificate chain that matches the server name.
Due to the early negotiation phase of the TLS connection, only limited methods and attributes are usable like [`SSLSocket.selected_alpn_protocol()`](#ssl.SSLSocket.selected_alpn_protocol "ssl.SSLSocket.selected_alpn_protocol") and [`SSLSocket.context`](#ssl.SSLSocket.context "ssl.SSLSocket.context"). [`SSLSocket.getpeercert()`](#ssl.SSLSocket.getpeercert "ssl.SSLSocket.getpeercert"), [`SSLSocket.getpeercert()`](#ssl.SSLSocket.getpeercert "ssl.SSLSocket.getpeercert"), [`SSLSocket.cipher()`](#ssl.SSLSocket.cipher "ssl.SSLSocket.cipher") and `SSLSocket.compress()` methods require that the TLS connection has progressed beyond the TLS Client Hello and therefore will not contain return meaningful values nor can they be called safely.
The *sni\_callback* function must return `None` to allow the TLS negotiation to continue. If a TLS failure is required, a constant [`ALERT_DESCRIPTION_*`](#ssl.ALERT_DESCRIPTION_INTERNAL_ERROR "ssl.ALERT_DESCRIPTION_INTERNAL_ERROR") can be returned. Other return values will result in a TLS fatal error with [`ALERT_DESCRIPTION_INTERNAL_ERROR`](#ssl.ALERT_DESCRIPTION_INTERNAL_ERROR "ssl.ALERT_DESCRIPTION_INTERNAL_ERROR").
If an exception is raised from the *sni\_callback* function the TLS connection will terminate with a fatal TLS alert message [`ALERT_DESCRIPTION_HANDSHAKE_FAILURE`](#ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE "ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE").
This method will raise [`NotImplementedError`](exceptions.xhtml#NotImplementedError "NotImplementedError") if the OpenSSL library had OPENSSL\_NO\_TLSEXT defined when it was built.
3\.7 新版功能.
`SSLContext.``set_servername_callback`(*server\_name\_callback*)This is a legacy API retained for backwards compatibility. When possible, you should use [`sni_callback`](#ssl.SSLContext.sni_callback "ssl.SSLContext.sni_callback") instead. The given *server\_name\_callback*is similar to *sni\_callback*, except that when the server hostname is an IDN-encoded internationalized domain name, the *server\_name\_callback*receives a decoded U-label (`"pythön.org"`).
If there is an decoding error on the server name, the TLS connection will terminate with an [`ALERT_DESCRIPTION_INTERNAL_ERROR`](#ssl.ALERT_DESCRIPTION_INTERNAL_ERROR "ssl.ALERT_DESCRIPTION_INTERNAL_ERROR") fatal TLS alert message to the client.
3\.4 新版功能.
`SSLContext.``load_dh_params`(*dhfile*)Load the key generation parameters for Diffie-Hellman (DH) key exchange. Using DH key exchange improves forward secrecy at the expense of computational resources (both on the server and on the client). The *dhfile* parameter should be the path to a file containing DH parameters in PEM format.
This setting doesn't apply to client sockets. You can also use the [`OP_SINGLE_DH_USE`](#ssl.OP_SINGLE_DH_USE "ssl.OP_SINGLE_DH_USE") option to further improve security.
3\.3 新版功能.
`SSLContext.``set_ecdh_curve`(*curve\_name*)Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key exchange. ECDH is significantly faster than regular DH while arguably as secure. The *curve\_name* parameter should be a string describing a well-known elliptic curve, for example `prime256v1` for a widely supported curve.
This setting doesn't apply to client sockets. You can also use the [`OP_SINGLE_ECDH_USE`](#ssl.OP_SINGLE_ECDH_USE "ssl.OP_SINGLE_ECDH_USE") option to further improve security.
This method is not available if [`HAS_ECDH`](#ssl.HAS_ECDH "ssl.HAS_ECDH") is `False`.
3\.3 新版功能.
参见
[SSL/TLS & Perfect Forward Secrecy](https://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy) \[https://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy\]Vincent Bernat.
`SSLContext.``wrap_socket`(*sock*, *server\_side=False*, *do\_handshake\_on\_connect=True*, *suppress\_ragged\_eofs=True*, *server\_hostname=None*, *session=None*)Wrap an existing Python socket *sock* and return an instance of [`SSLContext.sslsocket_class`](#ssl.SSLContext.sslsocket_class "ssl.SSLContext.sslsocket_class") (default [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket")). The returned SSL socket is tied to the context, its settings and certificates. *sock* must be a [`SOCK_STREAM`](socket.xhtml#socket.SOCK_STREAM "socket.SOCK_STREAM") socket; other socket types are unsupported.
The parameter `server_side` is a boolean which identifies whether server-side or client-side behavior is desired from this socket.
For client-side sockets, the context construction is lazy; if the underlying socket isn't connected yet, the context construction will be performed after `connect()` is called on the socket. For server-side sockets, if the socket has no remote peer, it is assumed to be a listening socket, and the server-side SSL wrapping is automatically performed on client connections accepted via the `accept()` method. The method may raise [`SSLError`](#ssl.SSLError "ssl.SSLError").
On client connections, the optional parameter *server\_hostname* specifies the hostname of the service which we are connecting to. This allows a single server to host multiple SSL-based services with distinct certificates, quite similarly to HTTP virtual hosts. Specifying *server\_hostname* will raise a [`ValueError`](exceptions.xhtml#ValueError "ValueError") if *server\_side* is true.
The parameter `do_handshake_on_connect` specifies whether to do the SSL handshake automatically after doing a `socket.connect()`, or whether the application program will call it explicitly, by invoking the [`SSLSocket.do_handshake()`](#ssl.SSLSocket.do_handshake "ssl.SSLSocket.do_handshake") method. Calling [`SSLSocket.do_handshake()`](#ssl.SSLSocket.do_handshake "ssl.SSLSocket.do_handshake") explicitly gives the program control over the blocking behavior of the socket I/O involved in the handshake.
The parameter `suppress_ragged_eofs` specifies how the `SSLSocket.recv()` method should signal unexpected EOF from the other end of the connection. If specified as [`True`](constants.xhtml#True "True") (the default), it returns a normal EOF (an empty bytes object) in response to unexpected EOF errors raised from the underlying socket; if [`False`](constants.xhtml#False "False"), it will raise the exceptions back to the caller.
*session*, see [`session`](#ssl.SSLSocket.session "ssl.SSLSocket.session").
在 3.5 版更改: Always allow a server\_hostname to be passed, even if OpenSSL does not have SNI.
在 3.6 版更改: *session* argument was added.
在 3.7 版更改: The method returns on instance of [`SSLContext.sslsocket_class`](#ssl.SSLContext.sslsocket_class "ssl.SSLContext.sslsocket_class")instead of hard-coded [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket").
`SSLContext.``sslsocket_class`The return type of `SSLContext.wrap_sockets()`, defaults to [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket"). The attribute can be overridden on instance of class in order to return a custom subclass of [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket").
3\.7 新版功能.
`SSLContext.``wrap_bio`(*incoming*, *outgoing*, *server\_side=False*, *server\_hostname=None*, *session=None*)Wrap the BIO objects *incoming* and *outgoing* and return an instance of attr:SSLContext.sslobject\_class (default [`SSLObject`](#ssl.SSLObject "ssl.SSLObject")). The SSL routines will read input data from the incoming BIO and write data to the outgoing BIO.
The *server\_side*, *server\_hostname* and *session* parameters have the same meaning as in [`SSLContext.wrap_socket()`](#ssl.SSLContext.wrap_socket "ssl.SSLContext.wrap_socket").
在 3.6 版更改: *session* argument was added.
在 3.7 版更改: The method returns on instance of [`SSLContext.sslobject_class`](#ssl.SSLContext.sslobject_class "ssl.SSLContext.sslobject_class")instead of hard-coded [`SSLObject`](#ssl.SSLObject "ssl.SSLObject").
`SSLContext.``sslobject_class`The return type of [`SSLContext.wrap_bio()`](#ssl.SSLContext.wrap_bio "ssl.SSLContext.wrap_bio"), defaults to [`SSLObject`](#ssl.SSLObject "ssl.SSLObject"). The attribute can be overridden on instance of class in order to return a custom subclass of [`SSLObject`](#ssl.SSLObject "ssl.SSLObject").
3\.7 新版功能.
`SSLContext.``session_stats`()Get statistics about the SSL sessions created or managed by this context. A dictionary is returned which maps the names of each [piece of information](https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_sess_number.html) \[https://www.openssl.org/docs/man1.1.0/ssl/SSL\_CTX\_sess\_number.html\] to their numeric values. For example, here is the total number of hits and misses in the session cache since the context was created:
```
>>> stats = context.session_stats()
>>> stats['hits'], stats['misses']
(0, 0)
```
`SSLContext.``check_hostname`Whether to match the peer cert's hostname with [`match_hostname()`](#ssl.match_hostname "ssl.match_hostname") in [`SSLSocket.do_handshake()`](#ssl.SSLSocket.do_handshake "ssl.SSLSocket.do_handshake"). The context's [`verify_mode`](#ssl.SSLContext.verify_mode "ssl.SSLContext.verify_mode") must be set to [`CERT_OPTIONAL`](#ssl.CERT_OPTIONAL "ssl.CERT_OPTIONAL") or [`CERT_REQUIRED`](#ssl.CERT_REQUIRED "ssl.CERT_REQUIRED"), and you must pass *server\_hostname* to [`wrap_socket()`](#ssl.SSLContext.wrap_socket "ssl.SSLContext.wrap_socket") in order to match the hostname. Enabling hostname checking automatically sets [`verify_mode`](#ssl.SSLContext.verify_mode "ssl.SSLContext.verify_mode") from [`CERT_NONE`](#ssl.CERT_NONE "ssl.CERT_NONE") to [`CERT_REQUIRED`](#ssl.CERT_REQUIRED "ssl.CERT_REQUIRED"). It cannot be set back to [`CERT_NONE`](#ssl.CERT_NONE "ssl.CERT_NONE") as long as hostname checking is enabled.
示例:
```
import socket, ssl
context = ssl.SSLContext()
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
context.load_default_certs()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com')
ssl_sock.connect(('www.verisign.com', 443))
```
3\.4 新版功能.
在 3.7 版更改: [`verify_mode`](#ssl.SSLContext.verify_mode "ssl.SSLContext.verify_mode") is now automatically changed to [`CERT_REQUIRED`](#ssl.CERT_REQUIRED "ssl.CERT_REQUIRED") when hostname checking is enabled and [`verify_mode`](#ssl.SSLContext.verify_mode "ssl.SSLContext.verify_mode") is [`CERT_NONE`](#ssl.CERT_NONE "ssl.CERT_NONE"). Previously the same operation would have failed with a [`ValueError`](exceptions.xhtml#ValueError "ValueError").
注解
This features requires OpenSSL 0.9.8f or newer.
`SSLContext.``maximum_version`A [`TLSVersion`](#ssl.TLSVersion "ssl.TLSVersion") enum member representing the highest supported TLS version. The value defaults to [`TLSVersion.MAXIMUM_SUPPORTED`](#ssl.TLSVersion.MAXIMUM_SUPPORTED "ssl.TLSVersion.MAXIMUM_SUPPORTED"). The attribute is read-only for protocols other than [`PROTOCOL_TLS`](#ssl.PROTOCOL_TLS "ssl.PROTOCOL_TLS"), [`PROTOCOL_TLS_CLIENT`](#ssl.PROTOCOL_TLS_CLIENT "ssl.PROTOCOL_TLS_CLIENT"), and [`PROTOCOL_TLS_SERVER`](#ssl.PROTOCOL_TLS_SERVER "ssl.PROTOCOL_TLS_SERVER").
The attributes [`maximum_version`](#ssl.SSLContext.maximum_version "ssl.SSLContext.maximum_version"), [`minimum_version`](#ssl.SSLContext.minimum_version "ssl.SSLContext.minimum_version") and [`SSLContext.options`](#ssl.SSLContext.options "ssl.SSLContext.options") all affect the supported SSL and TLS versions of the context. The implementation does not prevent invalid combination. For example a context with [`OP_NO_TLSv1_2`](#ssl.OP_NO_TLSv1_2 "ssl.OP_NO_TLSv1_2") in [`options`](#ssl.SSLContext.options "ssl.SSLContext.options") and [`maximum_version`](#ssl.SSLContext.maximum_version "ssl.SSLContext.maximum_version") set to [`TLSVersion.TLSv1_2`](#ssl.TLSVersion.TLSv1_2 "ssl.TLSVersion.TLSv1_2")will not be able to establish a TLS 1.2 connection.
注解
This attribute is not available unless the ssl module is compiled with OpenSSL 1.1.0g or newer.
3\.7 新版功能.
`SSLContext.``minimum_version`Like [`SSLContext.maximum_version`](#ssl.SSLContext.maximum_version "ssl.SSLContext.maximum_version") except it is the lowest supported version or [`TLSVersion.MINIMUM_SUPPORTED`](#ssl.TLSVersion.MINIMUM_SUPPORTED "ssl.TLSVersion.MINIMUM_SUPPORTED").
注解
This attribute is not available unless the ssl module is compiled with OpenSSL 1.1.0g or newer.
3\.7 新版功能.
`SSLContext.``options`An integer representing the set of SSL options enabled on this context. The default value is [`OP_ALL`](#ssl.OP_ALL "ssl.OP_ALL"), but you can specify other options such as [`OP_NO_SSLv2`](#ssl.OP_NO_SSLv2 "ssl.OP_NO_SSLv2") by ORing them together.
注解
With versions of OpenSSL older than 0.9.8m, it is only possible to set options, not to clear them. Attempting to clear an option (by resetting the corresponding bits) will raise a [`ValueError`](exceptions.xhtml#ValueError "ValueError").
在 3.6 版更改: [`SSLContext.options`](#ssl.SSLContext.options "ssl.SSLContext.options") returns [`Options`](#ssl.Options "ssl.Options") flags:
```
>>> ssl.create_default_context().options # doctest: +SKIP
<Options.OP_ALL|OP_NO_SSLv3|OP_NO_SSLv2|OP_NO_COMPRESSION: 2197947391>
```
`SSLContext.``post_handshake_auth`Enable TLS 1.3 post-handshake client authentication. Post-handshake auth is disabled by default and a server can only request a TLS client certificate during the initial handshake. When enabled, a server may request a TLS client certificate at any time after the handshake.
When enabled on client-side sockets, the client signals the server that it supports post-handshake authentication.
When enabled on server-side sockets, [`SSLContext.verify_mode`](#ssl.SSLContext.verify_mode "ssl.SSLContext.verify_mode") must be set to [`CERT_OPTIONAL`](#ssl.CERT_OPTIONAL "ssl.CERT_OPTIONAL") or [`CERT_REQUIRED`](#ssl.CERT_REQUIRED "ssl.CERT_REQUIRED"), too. The actual client cert exchange is delayed until [`SSLSocket.verify_client_post_handshake()`](#ssl.SSLSocket.verify_client_post_handshake "ssl.SSLSocket.verify_client_post_handshake") is called and some I/O is performed.
注解
Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 support, the property value is None and can't be modified
3\.7.1 新版功能.
`SSLContext.``protocol`The protocol version chosen when constructing the context. This attribute is read-only.
`SSLContext.``hostname_checks_common_name`Whether [`check_hostname`](#ssl.SSLContext.check_hostname "ssl.SSLContext.check_hostname") falls back to verify the cert's subject common name in the absence of a subject alternative name extension (default: true).
注解
Only writeable with OpenSSL 1.1.0 or higher.
3\.7 新版功能.
`SSLContext.``verify_flags`The flags for certificate verification operations. You can set flags like [`VERIFY_CRL_CHECK_LEAF`](#ssl.VERIFY_CRL_CHECK_LEAF "ssl.VERIFY_CRL_CHECK_LEAF") by ORing them together. By default OpenSSL does neither require nor verify certificate revocation lists (CRLs). Available only with openssl version 0.9.8+.
3\.4 新版功能.
在 3.6 版更改: [`SSLContext.verify_flags`](#ssl.SSLContext.verify_flags "ssl.SSLContext.verify_flags") returns [`VerifyFlags`](#ssl.VerifyFlags "ssl.VerifyFlags") flags:
```
>>> ssl.create_default_context().verify_flags # doctest: +SKIP
<VerifyFlags.VERIFY_X509_TRUSTED_FIRST: 32768>
```
`SSLContext.``verify_mode`Whether to try to verify other peers' certificates and how to behave if verification fails. This attribute must be one of [`CERT_NONE`](#ssl.CERT_NONE "ssl.CERT_NONE"), [`CERT_OPTIONAL`](#ssl.CERT_OPTIONAL "ssl.CERT_OPTIONAL") or [`CERT_REQUIRED`](#ssl.CERT_REQUIRED "ssl.CERT_REQUIRED").
在 3.6 版更改: [`SSLContext.verify_mode`](#ssl.SSLContext.verify_mode "ssl.SSLContext.verify_mode") returns [`VerifyMode`](#ssl.VerifyMode "ssl.VerifyMode") enum:
```
>>> ssl.create_default_context().verify_mode
<VerifyMode.CERT_REQUIRED: 2>
```
## Certificates
Certificates in general are part of a public-key / private-key system. In this system, each *principal*, (which may be a machine, or a person, or an organization) is assigned a unique two-part encryption key. One part of the key is public, and is called the *public key*; the other part is kept secret, and is called the *private key*. The two parts are related, in that if you encrypt a message with one of the parts, you can decrypt it with the other part, and **only** with the other part.
A certificate contains information about two principals. It contains the name of a *subject*, and the subject's public key. It also contains a statement by a second principal, the *issuer*, that the subject is who they claim to be, and that this is indeed the subject's public key. The issuer's statement is signed with the issuer's private key, which only the issuer knows. However, anyone can verify the issuer's statement by finding the issuer's public key, decrypting the statement with it, and comparing it to the other information in the certificate. The certificate also contains information about the time period over which it is valid. This is expressed as two fields, called "notBefore" and "notAfter".
In the Python use of certificates, a client or server can use a certificate to prove who they are. The other side of a network connection can also be required to produce a certificate, and that certificate can be validated to the satisfaction of the client or server that requires such validation. The connection attempt can be set to raise an exception if the validation fails. Validation is done automatically, by the underlying OpenSSL framework; the application need not concern itself with its mechanics. But the application does usually need to provide sets of certificates to allow this process to take place.
Python uses files to contain certificates. They should be formatted as "PEM" (see [**RFC 1422**](https://tools.ietf.org/html/rfc1422.html) \[https://tools.ietf.org/html/rfc1422.html\]), which is a base-64 encoded form wrapped with a header line and a footer line:
```
-----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----
```
### Certificate chains
The Python files which contain certificates can contain a sequence of certificates, sometimes called a *certificate chain*. This chain should start with the specific certificate for the principal who "is" the client or server, and then the certificate for the issuer of that certificate, and then the certificate for the issuer of *that* certificate, and so on up the chain till you get to a certificate which is *self-signed*, that is, a certificate which has the same subject and issuer, sometimes called a *root certificate*. The certificates should just be concatenated together in the certificate file. For example, suppose we had a three certificate chain, from our server certificate to the certificate of the certification authority that signed our server certificate, to the root certificate of the agency which issued the certification authority's certificate:
```
-----BEGIN CERTIFICATE-----
... (certificate for your server)...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... (the certificate for the CA)...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... (the root certificate for the CA's issuer)...
-----END CERTIFICATE-----
```
### CA certificates
If you are going to require validation of the other side of the connection's certificate, you need to provide a "CA certs" file, filled with the certificate chains for each issuer you are willing to trust. Again, this file just contains these chains concatenated together. For validation, Python will use the first chain it finds in the file which matches. The platform's certificates file can be used by calling [`SSLContext.load_default_certs()`](#ssl.SSLContext.load_default_certs "ssl.SSLContext.load_default_certs"), this is done automatically with [`create_default_context()`](#ssl.create_default_context "ssl.create_default_context").
### Combined key and certificate
Often the private key is stored in the same file as the certificate; in this case, only the `certfile` parameter to [`SSLContext.load_cert_chain()`](#ssl.SSLContext.load_cert_chain "ssl.SSLContext.load_cert_chain")and [`wrap_socket()`](#ssl.wrap_socket "ssl.wrap_socket") needs to be passed. If the private key is stored with the certificate, it should come before the first certificate in the certificate chain:
```
-----BEGIN RSA PRIVATE KEY-----
... (private key in base64 encoding) ...
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----
```
### Self-signed certificates
If you are going to create a server that provides SSL-encrypted connection services, you will need to acquire a certificate for that service. There are many ways of acquiring appropriate certificates, such as buying one from a certification authority. Another common practice is to generate a self-signed certificate. The simplest way to do this is with the OpenSSL package, using something like the following:
```
% openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
Generating a 1024 bit RSA private key
.......++++++
.............................++++++
writing new private key to 'cert.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:MyState
Locality Name (eg, city) []:Some City
Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
Organizational Unit Name (eg, section) []:My Group
Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
Email Address []:ops@myserver.mygroup.myorganization.com
%
```
The disadvantage of a self-signed certificate is that it is its own root certificate, and no one else will have it in their cache of known (and trusted) root certificates.
## 示例
### Testing for SSL support
To test for the presence of SSL support in a Python installation, user code should use the following idiom:
```
try:
import ssl
except ImportError:
pass
else:
... # do something that requires SSL support
```
### Client-side operation
This example creates a SSL context with the recommended security settings for client sockets, including automatic certificate verification:
```
>>> context = ssl.create_default_context()
```
If you prefer to tune security settings yourself, you might create a context from scratch (but beware that you might not get the settings right):
```
>>> context = ssl.SSLContext()
>>> context.verify_mode = ssl.CERT_REQUIRED
>>> context.check_hostname = True
>>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
```
(this snippet assumes your operating system places a bundle of all CA certificates in `/etc/ssl/certs/ca-bundle.crt`; if not, you'll get an error and have to adjust the location)
When you use the context to connect to a server, [`CERT_REQUIRED`](#ssl.CERT_REQUIRED "ssl.CERT_REQUIRED")validates the server certificate: it ensures that the server certificate was signed with one of the CA certificates, and checks the signature for correctness:
```
>>> conn = context.wrap_socket(socket.socket(socket.AF_INET),
... server_hostname="www.python.org")
>>> conn.connect(("www.python.org", 443))
```
You may then fetch the certificate:
```
>>> cert = conn.getpeercert()
```
Visual inspection shows that the certificate does identify the desired service (that is, the HTTPS host `www.python.org`):
```
>>> pprint.pprint(cert)
{'OCSP': ('http://ocsp.digicert.com',),
'caIssuers': ('http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt',),
'crlDistributionPoints': ('http://crl3.digicert.com/sha2-ev-server-g1.crl',
'http://crl4.digicert.com/sha2-ev-server-g1.crl'),
'issuer': ((('countryName', 'US'),),
(('organizationName', 'DigiCert Inc'),),
(('organizationalUnitName', 'www.digicert.com'),),
(('commonName', 'DigiCert SHA2 Extended Validation Server CA'),)),
'notAfter': 'Sep 9 12:00:00 2016 GMT',
'notBefore': 'Sep 5 00:00:00 2014 GMT',
'serialNumber': '01BB6F00122B177F36CAB49CEA8B6B26',
'subject': ((('businessCategory', 'Private Organization'),),
(('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
(('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
(('serialNumber', '3359300'),),
(('streetAddress', '16 Allen Rd'),),
(('postalCode', '03894-4801'),),
(('countryName', 'US'),),
(('stateOrProvinceName', 'NH'),),
(('localityName', 'Wolfeboro,'),),
(('organizationName', 'Python Software Foundation'),),
(('commonName', 'www.python.org'),)),
'subjectAltName': (('DNS', 'www.python.org'),
('DNS', 'python.org'),
('DNS', 'pypi.org'),
('DNS', 'docs.python.org'),
('DNS', 'testpypi.org'),
('DNS', 'bugs.python.org'),
('DNS', 'wiki.python.org'),
('DNS', 'hg.python.org'),
('DNS', 'mail.python.org'),
('DNS', 'packaging.python.org'),
('DNS', 'pythonhosted.org'),
('DNS', 'www.pythonhosted.org'),
('DNS', 'test.pythonhosted.org'),
('DNS', 'us.pycon.org'),
('DNS', 'id.python.org')),
'version': 3}
```
Now the SSL channel is established and the certificate verified, you can proceed to talk with the server:
```
>>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
>>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
[b'HTTP/1.1 200 OK',
b'Date: Sat, 18 Oct 2014 18:27:20 GMT',
b'Server: nginx',
b'Content-Type: text/html; charset=utf-8',
b'X-Frame-Options: SAMEORIGIN',
b'Content-Length: 45679',
b'Accept-Ranges: bytes',
b'Via: 1.1 varnish',
b'Age: 2188',
b'X-Served-By: cache-lcy1134-LCY',
b'X-Cache: HIT',
b'X-Cache-Hits: 11',
b'Vary: Cookie',
b'Strict-Transport-Security: max-age=63072000; includeSubDomains',
b'Connection: close',
b'',
b'']
```
See the discussion of [Security considerations](#ssl-security) below.
### Server-side operation
For server operation, typically you'll need to have a server certificate, and private key, each in a file. You'll first create a context holding the key and the certificate, so that clients can check your authenticity. Then you'll open a socket, bind it to a port, call `listen()` on it, and start waiting for clients to connect:
```
import socket, ssl
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")
bindsocket = socket.socket()
bindsocket.bind(('myaddr.mydomain.com', 10023))
bindsocket.listen(5)
```
When a client connects, you'll call `accept()` on the socket to get the new socket from the other end, and use the context's [`SSLContext.wrap_socket()`](#ssl.SSLContext.wrap_socket "ssl.SSLContext.wrap_socket")method to create a server-side SSL socket for the connection:
```
while True:
newsocket, fromaddr = bindsocket.accept()
connstream = context.wrap_socket(newsocket, server_side=True)
try:
deal_with_client(connstream)
finally:
connstream.shutdown(socket.SHUT_RDWR)
connstream.close()
```
Then you'll read data from the `connstream` and do something with it till you are finished with the client (or the client is finished with you):
```
def deal_with_client(connstream):
data = connstream.recv(1024)
# empty data means the client is finished with us
while data:
if not do_something(connstream, data):
# we'll assume do_something returns False
# when we're finished with client
break
data = connstream.recv(1024)
# finished with client
```
And go back to listening for new client connections (of course, a real server would probably handle each client connection in a separate thread, or put the sockets in [non-blocking mode](#ssl-nonblocking) and use an event loop).
## Notes on non-blocking sockets
SSL sockets behave slightly different than regular sockets in non-blocking mode. When working with non-blocking sockets, there are thus several things you need to be aware of:
- Most [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket") methods will raise either [`SSLWantWriteError`](#ssl.SSLWantWriteError "ssl.SSLWantWriteError") or [`SSLWantReadError`](#ssl.SSLWantReadError "ssl.SSLWantReadError") instead of [`BlockingIOError`](exceptions.xhtml#BlockingIOError "BlockingIOError") if an I/O operation would block. [`SSLWantReadError`](#ssl.SSLWantReadError "ssl.SSLWantReadError") will be raised if a read operation on the underlying socket is necessary, and [`SSLWantWriteError`](#ssl.SSLWantWriteError "ssl.SSLWantWriteError") for a write operation on the underlying socket. Note that attempts to *write* to an SSL socket may require *reading* from the underlying socket first, and attempts to *read* from the SSL socket may require a prior *write* to the underlying socket.
在 3.5 版更改: In earlier Python versions, the `SSLSocket.send()` method returned zero instead of raising [`SSLWantWriteError`](#ssl.SSLWantWriteError "ssl.SSLWantWriteError") or [`SSLWantReadError`](#ssl.SSLWantReadError "ssl.SSLWantReadError").
- Calling [`select()`](select.xhtml#select.select "select.select") tells you that the OS-level socket can be read from (or written to), but it does not imply that there is sufficient data at the upper SSL layer. For example, only part of an SSL frame might have arrived. Therefore, you must be ready to handle `SSLSocket.recv()`and `SSLSocket.send()` failures, and retry after another call to [`select()`](select.xhtml#select.select "select.select").
- Conversely, since the SSL layer has its own framing, a SSL socket may still have data available for reading without [`select()`](select.xhtml#select.select "select.select")being aware of it. Therefore, you should first call `SSLSocket.recv()` to drain any potentially available data, and then only block on a [`select()`](select.xhtml#select.select "select.select") call if still necessary.
(of course, similar provisions apply when using other primitives such as [`poll()`](select.xhtml#select.poll "select.poll"), or those in the [`selectors`](selectors.xhtml#module-selectors "selectors: High-level I/O multiplexing.") module)
- The SSL handshake itself will be non-blocking: the [`SSLSocket.do_handshake()`](#ssl.SSLSocket.do_handshake "ssl.SSLSocket.do_handshake") method has to be retried until it returns successfully. Here is a synopsis using [`select()`](select.xhtml#select.select "select.select") to wait for the socket's readiness:
```
while True:
try:
sock.do_handshake()
break
except ssl.SSLWantReadError:
select.select([sock], [], [])
except ssl.SSLWantWriteError:
select.select([], [sock], [])
```
参见
The [`asyncio`](asyncio.xhtml#module-asyncio "asyncio: Asynchronous I/O.") module supports [non-blocking SSL sockets](#ssl-nonblocking) and provides a higher level API. It polls for events using the [`selectors`](selectors.xhtml#module-selectors "selectors: High-level I/O multiplexing.") module and handles [`SSLWantWriteError`](#ssl.SSLWantWriteError "ssl.SSLWantWriteError"), [`SSLWantReadError`](#ssl.SSLWantReadError "ssl.SSLWantReadError") and [`BlockingIOError`](exceptions.xhtml#BlockingIOError "BlockingIOError") exceptions. It runs the SSL handshake asynchronously as well.
## Memory BIO Support
3\.5 新版功能.
Ever since the SSL module was introduced in Python 2.6, the [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket")class has provided two related but distinct areas of functionality:
- SSL protocol handling
- Network IO
The network IO API is identical to that provided by [`socket.socket`](socket.xhtml#socket.socket "socket.socket"), from which [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket") also inherits. This allows an SSL socket to be used as a drop-in replacement for a regular socket, making it very easy to add SSL support to an existing application.
Combining SSL protocol handling and network IO usually works well, but there are some cases where it doesn't. An example is async IO frameworks that want to use a different IO multiplexing model than the "select/poll on a file descriptor" (readiness based) model that is assumed by [`socket.socket`](socket.xhtml#socket.socket "socket.socket")and by the internal OpenSSL socket IO routines. This is mostly relevant for platforms like Windows where this model is not efficient. For this purpose, a reduced scope variant of [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket") called [`SSLObject`](#ssl.SSLObject "ssl.SSLObject") is provided.
*class* `ssl.``SSLObject`A reduced-scope variant of [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket") representing an SSL protocol instance that does not contain any network IO methods. This class is typically used by framework authors that want to implement asynchronous IO for SSL through memory buffers.
This class implements an interface on top of a low-level SSL object as implemented by OpenSSL. This object captures the state of an SSL connection but does not provide any network IO itself. IO needs to be performed through separate "BIO" objects which are OpenSSL's IO abstraction layer.
This class has no public constructor. An [`SSLObject`](#ssl.SSLObject "ssl.SSLObject") instance must be created using the [`wrap_bio()`](#ssl.SSLContext.wrap_bio "ssl.SSLContext.wrap_bio") method. This method will create the [`SSLObject`](#ssl.SSLObject "ssl.SSLObject") instance and bind it to a pair of BIOs. The *incoming* BIO is used to pass data from Python to the SSL protocol instance, while the *outgoing* BIO is used to pass data the other way around.
The following methods are available:
- [`context`](#ssl.SSLSocket.context "ssl.SSLSocket.context")
- [`server_side`](#ssl.SSLSocket.server_side "ssl.SSLSocket.server_side")
- [`server_hostname`](#ssl.SSLSocket.server_hostname "ssl.SSLSocket.server_hostname")
- [`session`](#ssl.SSLSocket.session "ssl.SSLSocket.session")
- [`session_reused`](#ssl.SSLSocket.session_reused "ssl.SSLSocket.session_reused")
- [`read()`](#ssl.SSLSocket.read "ssl.SSLSocket.read")
- [`write()`](#ssl.SSLSocket.write "ssl.SSLSocket.write")
- [`getpeercert()`](#ssl.SSLSocket.getpeercert "ssl.SSLSocket.getpeercert")
- [`selected_npn_protocol()`](#ssl.SSLSocket.selected_npn_protocol "ssl.SSLSocket.selected_npn_protocol")
- [`cipher()`](#ssl.SSLSocket.cipher "ssl.SSLSocket.cipher")
- [`shared_ciphers()`](#ssl.SSLSocket.shared_ciphers "ssl.SSLSocket.shared_ciphers")
- [`compression()`](#ssl.SSLSocket.compression "ssl.SSLSocket.compression")
- [`pending()`](#ssl.SSLSocket.pending "ssl.SSLSocket.pending")
- [`do_handshake()`](#ssl.SSLSocket.do_handshake "ssl.SSLSocket.do_handshake")
- [`unwrap()`](#ssl.SSLSocket.unwrap "ssl.SSLSocket.unwrap")
- [`get_channel_binding()`](#ssl.SSLSocket.get_channel_binding "ssl.SSLSocket.get_channel_binding")
When compared to [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket"), this object lacks the following features:
- Any form of network IO; `recv()` and `send()` read and write only to the underlying [`MemoryBIO`](#ssl.MemoryBIO "ssl.MemoryBIO") buffers.
- There is no *do\_handshake\_on\_connect* machinery. You must always manually call [`do_handshake()`](#ssl.SSLSocket.do_handshake "ssl.SSLSocket.do_handshake") to start the handshake.
- There is no handling of *suppress\_ragged\_eofs*. All end-of-file conditions that are in violation of the protocol are reported via the [`SSLEOFError`](#ssl.SSLEOFError "ssl.SSLEOFError") exception.
- The method [`unwrap()`](#ssl.SSLSocket.unwrap "ssl.SSLSocket.unwrap") call does not return anything, unlike for an SSL socket where it returns the underlying socket.
- The *server\_name\_callback* callback passed to [`SSLContext.set_servername_callback()`](#ssl.SSLContext.set_servername_callback "ssl.SSLContext.set_servername_callback") will get an [`SSLObject`](#ssl.SSLObject "ssl.SSLObject")instance instead of a [`SSLSocket`](#ssl.SSLSocket "ssl.SSLSocket") instance as its first parameter.
Some notes related to the use of [`SSLObject`](#ssl.SSLObject "ssl.SSLObject"):
- All IO on an [`SSLObject`](#ssl.SSLObject "ssl.SSLObject") is [non-blocking](#ssl-nonblocking). This means that for example [`read()`](#ssl.SSLSocket.read "ssl.SSLSocket.read") will raise an [`SSLWantReadError`](#ssl.SSLWantReadError "ssl.SSLWantReadError") if it needs more data than the incoming BIO has available.
- There is no module-level `wrap_bio()` call like there is for [`wrap_socket()`](#ssl.SSLContext.wrap_socket "ssl.SSLContext.wrap_socket"). An [`SSLObject`](#ssl.SSLObject "ssl.SSLObject") is always created via an [`SSLContext`](#ssl.SSLContext "ssl.SSLContext").
在 3.7 版更改: [`SSLObject`](#ssl.SSLObject "ssl.SSLObject") instances must to created with [`wrap_bio()`](#ssl.SSLContext.wrap_bio "ssl.SSLContext.wrap_bio"). In earlier versions, it was possible to create instances directly. This was never documented or officially supported.
An SSLObject communicates with the outside world using memory buffers. The class [`MemoryBIO`](#ssl.MemoryBIO "ssl.MemoryBIO") provides a memory buffer that can be used for this purpose. It wraps an OpenSSL memory BIO (Basic IO) object:
*class* `ssl.``MemoryBIO`A memory buffer that can be used to pass data between Python and an SSL protocol instance.
`pending`Return the number of bytes currently in the memory buffer.
`eof`A boolean indicating whether the memory BIO is current at the end-of-file position.
`read`(*n=-1*)Read up to *n* bytes from the memory buffer. If *n* is not specified or negative, all bytes are returned.
`write`(*buf*)Write the bytes from *buf* to the memory BIO. The *buf* argument must be an object supporting the buffer protocol.
The return value is the number of bytes written, which is always equal to the length of *buf*.
`write_eof`()Write an EOF marker to the memory BIO. After this method has been called, it is illegal to call [`write()`](#ssl.MemoryBIO.write "ssl.MemoryBIO.write"). The attribute [`eof`](#ssl.MemoryBIO.eof "ssl.MemoryBIO.eof") will become true after all data currently in the buffer has been read.
## SSL session
3\.6 新版功能.
*class* `ssl.``SSLSession`Session object used by [`session`](#ssl.SSLSocket.session "ssl.SSLSocket.session").
`id``time``timeout``ticket_lifetime_hint``has_ticket`
## Security considerations
### Best defaults
For **client use**, if you don't have any special requirements for your security policy, it is highly recommended that you use the [`create_default_context()`](#ssl.create_default_context "ssl.create_default_context") function to create your SSL context. It will load the system's trusted CA certificates, enable certificate validation and hostname checking, and try to choose reasonably secure protocol and cipher settings.
For example, here is how you would use the [`smtplib.SMTP`](smtplib.xhtml#smtplib.SMTP "smtplib.SMTP") class to create a trusted, secure connection to a SMTP server:
```
>>> import ssl, smtplib
>>> smtp = smtplib.SMTP("mail.python.org", port=587)
>>> context = ssl.create_default_context()
>>> smtp.starttls(context=context)
(220, b'2.0.0 Ready to start TLS')
```
If a client certificate is needed for the connection, it can be added with [`SSLContext.load_cert_chain()`](#ssl.SSLContext.load_cert_chain "ssl.SSLContext.load_cert_chain").
By contrast, if you create the SSL context by calling the [`SSLContext`](#ssl.SSLContext "ssl.SSLContext")constructor yourself, it will not have certificate validation nor hostname checking enabled by default. If you do so, please read the paragraphs below to achieve a good security level.
### Manual settings
#### Verifying certificates
When calling the [`SSLContext`](#ssl.SSLContext "ssl.SSLContext") constructor directly, [`CERT_NONE`](#ssl.CERT_NONE "ssl.CERT_NONE") is the default. Since it does not authenticate the other peer, it can be insecure, especially in client mode where most of time you would like to ensure the authenticity of the server you're talking to. Therefore, when in client mode, it is highly recommended to use [`CERT_REQUIRED`](#ssl.CERT_REQUIRED "ssl.CERT_REQUIRED"). However, it is in itself not sufficient; you also have to check that the server certificate, which can be obtained by calling [`SSLSocket.getpeercert()`](#ssl.SSLSocket.getpeercert "ssl.SSLSocket.getpeercert"), matches the desired service. For many protocols and applications, the service can be identified by the hostname; in this case, the [`match_hostname()`](#ssl.match_hostname "ssl.match_hostname") function can be used. This common check is automatically performed when [`SSLContext.check_hostname`](#ssl.SSLContext.check_hostname "ssl.SSLContext.check_hostname") is enabled.
在 3.7 版更改: Hostname matchings is now performed by OpenSSL. Python no longer uses [`match_hostname()`](#ssl.match_hostname "ssl.match_hostname").
In server mode, if you want to authenticate your clients using the SSL layer (rather than using a higher-level authentication mechanism), you'll also have to specify [`CERT_REQUIRED`](#ssl.CERT_REQUIRED "ssl.CERT_REQUIRED") and similarly check the client certificate.
#### Protocol versions
SSL versions 2 and 3 are considered insecure and are therefore dangerous to use. If you want maximum compatibility between clients and servers, it is recommended to use [`PROTOCOL_TLS_CLIENT`](#ssl.PROTOCOL_TLS_CLIENT "ssl.PROTOCOL_TLS_CLIENT") or [`PROTOCOL_TLS_SERVER`](#ssl.PROTOCOL_TLS_SERVER "ssl.PROTOCOL_TLS_SERVER") as the protocol version. SSLv2 and SSLv3 are disabled by default.
```
>>> client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
>>> client_context.options |= ssl.OP_NO_TLSv1
>>> client_context.options |= ssl.OP_NO_TLSv1_1
```
The SSL context created above will only allow TLSv1.2 and later (if supported by your system) connections to a server. [`PROTOCOL_TLS_CLIENT`](#ssl.PROTOCOL_TLS_CLIENT "ssl.PROTOCOL_TLS_CLIENT")implies certificate validation and hostname checks by default. You have to load certificates into the context.
#### Cipher selection
If you have advanced security requirements, fine-tuning of the ciphers enabled when negotiating a SSL session is possible through the [`SSLContext.set_ciphers()`](#ssl.SSLContext.set_ciphers "ssl.SSLContext.set_ciphers") method. Starting from Python 3.2.3, the ssl module disables certain weak ciphers by default, but you may want to further restrict the cipher choice. Be sure to read OpenSSL's documentation about the [cipher list format](https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT) \[https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT\]. If you want to check which ciphers are enabled by a given cipher list, use [`SSLContext.get_ciphers()`](#ssl.SSLContext.get_ciphers "ssl.SSLContext.get_ciphers") or the `openssl ciphers` command on your system.
### Multi-processing
If using this module as part of a multi-processed application (using, for example the [`multiprocessing`](multiprocessing.xhtml#module-multiprocessing "multiprocessing: Process-based parallelism.") or [`concurrent.futures`](concurrent.futures.xhtml#module-concurrent.futures "concurrent.futures: Execute computations concurrently using threads or processes.") modules), be aware that OpenSSL's internal random number generator does not properly handle forked processes. Applications must change the PRNG state of the parent process if they use any SSL feature with [`os.fork()`](os.xhtml#os.fork "os.fork"). Any successful call of [`RAND_add()`](#ssl.RAND_add "ssl.RAND_add"), [`RAND_bytes()`](#ssl.RAND_bytes "ssl.RAND_bytes") or [`RAND_pseudo_bytes()`](#ssl.RAND_pseudo_bytes "ssl.RAND_pseudo_bytes") is sufficient.
## TLS 1.3
3\.7 新版功能.
Python has provisional and experimental support for TLS 1.3 with OpenSSL 1.1.1. The new protocol behaves slightly differently than previous version of TLS/SSL. Some new TLS 1.3 features are not yet available.
- TLS 1.3 uses a disjunct set of cipher suites. All AES-GCM and ChaCha20 cipher suites are enabled by default. The method [`SSLContext.set_ciphers()`](#ssl.SSLContext.set_ciphers "ssl.SSLContext.set_ciphers") cannot enable or disable any TLS 1.3 ciphers yet, but [`SSLContext.get_ciphers()`](#ssl.SSLContext.get_ciphers "ssl.SSLContext.get_ciphers") returns them.
- Session tickets are no longer sent as part of the initial handshake and are handled differently. [`SSLSocket.session`](#ssl.SSLSocket.session "ssl.SSLSocket.session") and [`SSLSession`](#ssl.SSLSession "ssl.SSLSession")are not compatible with TLS 1.3.
- Client-side certificates are also no longer verified during the initial handshake. A server can request a certificate at any time. Clients process certificate requests while they send or receive application data from the server.
- TLS 1.3 features like early data, deferred TLS client cert request, signature algorithm configuration, and rekeying are not supported yet.
## LibreSSL support
LibreSSL is a fork of OpenSSL 1.0.1. The ssl module has limited support for LibreSSL. Some features are not available when the ssl module is compiled with LibreSSL.
- LibreSSL >= 2.6.1 no longer supports NPN. The methods [`SSLContext.set_npn_protocols()`](#ssl.SSLContext.set_npn_protocols "ssl.SSLContext.set_npn_protocols") and [`SSLSocket.selected_npn_protocol()`](#ssl.SSLSocket.selected_npn_protocol "ssl.SSLSocket.selected_npn_protocol") are not available.
- [`SSLContext.set_default_verify_paths()`](#ssl.SSLContext.set_default_verify_paths "ssl.SSLContext.set_default_verify_paths") ignores the env vars `SSL_CERT_FILE` and `SSL_CERT_PATH` although [`get_default_verify_paths()`](#ssl.get_default_verify_paths "ssl.get_default_verify_paths") still reports them.
参见
Class [`socket.socket`](socket.xhtml#socket.socket "socket.socket")Documentation of underlying [`socket`](socket.xhtml#module-socket "socket: Low-level networking interface.") class
[SSL/TLS Strong Encryption: An Introduction](https://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html) \[https://httpd.apache.org/docs/trunk/en/ssl/ssl\_intro.html\]Intro from the Apache HTTP Server documentation
[**RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management**](https://tools.ietf.org/html/rfc1422.html) \[https://tools.ietf.org/html/rfc1422.html\]Steve Kent
[**RFC 4086: Randomness Requirements for Security**](https://tools.ietf.org/html/rfc4086.html) \[https://tools.ietf.org/html/rfc4086.html\]Donald E., Jeffrey I. Schiller
[**RFC 5280: Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile**](https://tools.ietf.org/html/rfc5280.html) \[https://tools.ietf.org/html/rfc5280.html\]D. Cooper
[**RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2**](https://tools.ietf.org/html/rfc5246.html) \[https://tools.ietf.org/html/rfc5246.html\]T. Dierks et. al.
[**RFC 6066: Transport Layer Security (TLS) Extensions**](https://tools.ietf.org/html/rfc6066.html) \[https://tools.ietf.org/html/rfc6066.html\]D. Eastlake
[IANA TLS: Transport Layer Security (TLS) Parameters](https://www.iana.org/assignments/tls-parameters/tls-parameters.xml) \[https://www.iana.org/assignments/tls-parameters/tls-parameters.xml\]IANA
[**RFC 7525: Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS)**](https://tools.ietf.org/html/rfc7525.html) \[https://tools.ietf.org/html/rfc7525.html\]IETF
[Mozilla's Server Side TLS recommendations](https://wiki.mozilla.org/Security/Server_Side_TLS) \[https://wiki.mozilla.org/Security/Server\_Side\_TLS\]Mozilla
### 导航
- [索引](../genindex.xhtml "总目录")
- [模块](../py-modindex.xhtml "Python 模块索引") |
- [下一页](select.xhtml "select --- Waiting for I/O completion") |
- [上一页](socket.xhtml "socket --- 底层网络接口") |
- ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png)
- [Python](https://www.python.org/) »
- zh\_CN 3.7.3 [文档](../index.xhtml) »
- [Python 标准库](index.xhtml) »
- [网络和进程间通信](ipc.xhtml) »
- $('.inline-search').show(0); |
© [版权所有](../copyright.xhtml) 2001-2019, Python Software Foundation.
Python 软件基金会是一个非盈利组织。 [请捐助。](https://www.python.org/psf/donations/)
最后更新于 5月 21, 2019. [发现了问题](../bugs.xhtml)?
使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 创建。
- Python文档内容
- Python 有什么新变化?
- Python 3.7 有什么新变化
- 摘要 - 发布重点
- 新的特性
- 其他语言特性修改
- 新增模块
- 改进的模块
- C API 的改变
- 构建的改变
- 性能优化
- 其他 CPython 实现的改变
- 已弃用的 Python 行为
- 已弃用的 Python 模块、函数和方法
- 已弃用的 C API 函数和类型
- 平台支持的移除
- API 与特性的移除
- 移除的模块
- Windows 专属的改变
- 移植到 Python 3.7
- Python 3.7.1 中的重要变化
- Python 3.7.2 中的重要变化
- Python 3.6 有什么新变化A
- 摘要 - 发布重点
- 新的特性
- 其他语言特性修改
- 新增模块
- 改进的模块
- 性能优化
- Build and C API Changes
- 其他改进
- 弃用
- 移除
- 移植到Python 3.6
- Python 3.6.2 中的重要变化
- Python 3.6.4 中的重要变化
- Python 3.6.5 中的重要变化
- Python 3.6.7 中的重要变化
- Python 3.5 有什么新变化
- 摘要 - 发布重点
- 新的特性
- 其他语言特性修改
- 新增模块
- 改进的模块
- Other module-level changes
- 性能优化
- Build and C API Changes
- 弃用
- 移除
- Porting to Python 3.5
- Notable changes in Python 3.5.4
- What's New In Python 3.4
- 摘要 - 发布重点
- 新的特性
- 新增模块
- 改进的模块
- CPython Implementation Changes
- 弃用
- 移除
- Porting to Python 3.4
- Changed in 3.4.3
- What's New In Python 3.3
- 摘要 - 发布重点
- PEP 405: Virtual Environments
- PEP 420: Implicit Namespace Packages
- PEP 3118: New memoryview implementation and buffer protocol documentation
- PEP 393: Flexible String Representation
- PEP 397: Python Launcher for Windows
- PEP 3151: Reworking the OS and IO exception hierarchy
- PEP 380: Syntax for Delegating to a Subgenerator
- PEP 409: Suppressing exception context
- PEP 414: Explicit Unicode literals
- PEP 3155: Qualified name for classes and functions
- PEP 412: Key-Sharing Dictionary
- PEP 362: Function Signature Object
- PEP 421: Adding sys.implementation
- Using importlib as the Implementation of Import
- 其他语言特性修改
- A Finer-Grained Import Lock
- Builtin functions and types
- 新增模块
- 改进的模块
- 性能优化
- Build and C API Changes
- 弃用
- Porting to Python 3.3
- What's New In Python 3.2
- PEP 384: Defining a Stable ABI
- PEP 389: Argparse Command Line Parsing Module
- PEP 391: Dictionary Based Configuration for Logging
- PEP 3148: The concurrent.futures module
- PEP 3147: PYC Repository Directories
- PEP 3149: ABI Version Tagged .so Files
- PEP 3333: Python Web Server Gateway Interface v1.0.1
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- 多线程
- 性能优化
- Unicode
- Codecs
- 文档
- IDLE
- Code Repository
- Build and C API Changes
- Porting to Python 3.2
- What's New In Python 3.1
- PEP 372: Ordered Dictionaries
- PEP 378: Format Specifier for Thousands Separator
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- 性能优化
- IDLE
- Build and C API Changes
- Porting to Python 3.1
- What's New In Python 3.0
- Common Stumbling Blocks
- Overview Of Syntax Changes
- Changes Already Present In Python 2.6
- Library Changes
- PEP 3101: A New Approach To String Formatting
- Changes To Exceptions
- Miscellaneous Other Changes
- Build and C API Changes
- 性能
- Porting To Python 3.0
- What's New in Python 2.7
- The Future for Python 2.x
- Changes to the Handling of Deprecation Warnings
- Python 3.1 Features
- PEP 372: Adding an Ordered Dictionary to collections
- PEP 378: Format Specifier for Thousands Separator
- PEP 389: The argparse Module for Parsing Command Lines
- PEP 391: Dictionary-Based Configuration For Logging
- PEP 3106: Dictionary Views
- PEP 3137: The memoryview Object
- 其他语言特性修改
- New and Improved Modules
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.7
- New Features Added to Python 2.7 Maintenance Releases
- Acknowledgements
- Python 2.6 有什么新变化
- Python 3.0
- Changes to the Development Process
- PEP 343: The 'with' statement
- PEP 366: Explicit Relative Imports From a Main Module
- PEP 370: Per-user site-packages Directory
- PEP 371: The multiprocessing Package
- PEP 3101: Advanced String Formatting
- PEP 3105: print As a Function
- PEP 3110: Exception-Handling Changes
- PEP 3112: Byte Literals
- PEP 3116: New I/O Library
- PEP 3118: Revised Buffer Protocol
- PEP 3119: Abstract Base Classes
- PEP 3127: Integer Literal Support and Syntax
- PEP 3129: Class Decorators
- PEP 3141: A Type Hierarchy for Numbers
- 其他语言特性修改
- New and Improved Modules
- Deprecations and Removals
- Build and C API Changes
- Porting to Python 2.6
- Acknowledgements
- What's New in Python 2.5
- PEP 308: Conditional Expressions
- PEP 309: Partial Function Application
- PEP 314: Metadata for Python Software Packages v1.1
- PEP 328: Absolute and Relative Imports
- PEP 338: Executing Modules as Scripts
- PEP 341: Unified try/except/finally
- PEP 342: New Generator Features
- PEP 343: The 'with' statement
- PEP 352: Exceptions as New-Style Classes
- PEP 353: Using ssize_t as the index type
- PEP 357: The 'index' method
- 其他语言特性修改
- New, Improved, and Removed Modules
- Build and C API Changes
- Porting to Python 2.5
- Acknowledgements
- What's New in Python 2.4
- PEP 218: Built-In Set Objects
- PEP 237: Unifying Long Integers and Integers
- PEP 289: Generator Expressions
- PEP 292: Simpler String Substitutions
- PEP 318: Decorators for Functions and Methods
- PEP 322: Reverse Iteration
- PEP 324: New subprocess Module
- PEP 327: Decimal Data Type
- PEP 328: Multi-line Imports
- PEP 331: Locale-Independent Float/String Conversions
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- Build and C API Changes
- Porting to Python 2.4
- Acknowledgements
- What's New in Python 2.3
- PEP 218: A Standard Set Datatype
- PEP 255: Simple Generators
- PEP 263: Source Code Encodings
- PEP 273: Importing Modules from ZIP Archives
- PEP 277: Unicode file name support for Windows NT
- PEP 278: Universal Newline Support
- PEP 279: enumerate()
- PEP 282: The logging Package
- PEP 285: A Boolean Type
- PEP 293: Codec Error Handling Callbacks
- PEP 301: Package Index and Metadata for Distutils
- PEP 302: New Import Hooks
- PEP 305: Comma-separated Files
- PEP 307: Pickle Enhancements
- Extended Slices
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- Pymalloc: A Specialized Object Allocator
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.3
- Acknowledgements
- What's New in Python 2.2
- 概述
- PEPs 252 and 253: Type and Class Changes
- PEP 234: Iterators
- PEP 255: Simple Generators
- PEP 237: Unifying Long Integers and Integers
- PEP 238: Changing the Division Operator
- Unicode Changes
- PEP 227: Nested Scopes
- New and Improved Modules
- Interpreter Changes and Fixes
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.1
- 概述
- PEP 227: Nested Scopes
- PEP 236: future Directives
- PEP 207: Rich Comparisons
- PEP 230: Warning Framework
- PEP 229: New Build System
- PEP 205: Weak References
- PEP 232: Function Attributes
- PEP 235: Importing Modules on Case-Insensitive Platforms
- PEP 217: Interactive Display Hook
- PEP 208: New Coercion Model
- PEP 241: Metadata in Python Packages
- New and Improved Modules
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.0
- 概述
- What About Python 1.6?
- New Development Process
- Unicode
- 列表推导式
- Augmented Assignment
- 字符串的方法
- Garbage Collection of Cycles
- Other Core Changes
- Porting to 2.0
- Extending/Embedding Changes
- Distutils: Making Modules Easy to Install
- XML Modules
- Module changes
- New modules
- IDLE Improvements
- Deleted and Deprecated Modules
- Acknowledgements
- 更新日志
- Python 下一版
- Python 3.7.3 最终版
- Python 3.7.3 发布候选版 1
- Python 3.7.2 最终版
- Python 3.7.2 发布候选版 1
- Python 3.7.1 最终版
- Python 3.7.1 RC 2版本
- Python 3.7.1 发布候选版 1
- Python 3.7.0 正式版
- Python 3.7.0 release candidate 1
- Python 3.7.0 beta 5
- Python 3.7.0 beta 4
- Python 3.7.0 beta 3
- Python 3.7.0 beta 2
- Python 3.7.0 beta 1
- Python 3.7.0 alpha 4
- Python 3.7.0 alpha 3
- Python 3.7.0 alpha 2
- Python 3.7.0 alpha 1
- Python 3.6.6 final
- Python 3.6.6 RC 1
- Python 3.6.5 final
- Python 3.6.5 release candidate 1
- Python 3.6.4 final
- Python 3.6.4 release candidate 1
- Python 3.6.3 final
- Python 3.6.3 release candidate 1
- Python 3.6.2 final
- Python 3.6.2 release candidate 2
- Python 3.6.2 release candidate 1
- Python 3.6.1 final
- Python 3.6.1 release candidate 1
- Python 3.6.0 final
- Python 3.6.0 release candidate 2
- Python 3.6.0 release candidate 1
- Python 3.6.0 beta 4
- Python 3.6.0 beta 3
- Python 3.6.0 beta 2
- Python 3.6.0 beta 1
- Python 3.6.0 alpha 4
- Python 3.6.0 alpha 3
- Python 3.6.0 alpha 2
- Python 3.6.0 alpha 1
- Python 3.5.5 final
- Python 3.5.5 release candidate 1
- Python 3.5.4 final
- Python 3.5.4 release candidate 1
- Python 3.5.3 final
- Python 3.5.3 release candidate 1
- Python 3.5.2 final
- Python 3.5.2 release candidate 1
- Python 3.5.1 final
- Python 3.5.1 release candidate 1
- Python 3.5.0 final
- Python 3.5.0 release candidate 4
- Python 3.5.0 release candidate 3
- Python 3.5.0 release candidate 2
- Python 3.5.0 release candidate 1
- Python 3.5.0 beta 4
- Python 3.5.0 beta 3
- Python 3.5.0 beta 2
- Python 3.5.0 beta 1
- Python 3.5.0 alpha 4
- Python 3.5.0 alpha 3
- Python 3.5.0 alpha 2
- Python 3.5.0 alpha 1
- Python 教程
- 课前甜点
- 使用 Python 解释器
- 调用解释器
- 解释器的运行环境
- Python 的非正式介绍
- Python 作为计算器使用
- 走向编程的第一步
- 其他流程控制工具
- if 语句
- for 语句
- range() 函数
- break 和 continue 语句,以及循环中的 else 子句
- pass 语句
- 定义函数
- 函数定义的更多形式
- 小插曲:编码风格
- 数据结构
- 列表的更多特性
- del 语句
- 元组和序列
- 集合
- 字典
- 循环的技巧
- 深入条件控制
- 序列和其它类型的比较
- 模块
- 有关模块的更多信息
- 标准模块
- dir() 函数
- 包
- 输入输出
- 更漂亮的输出格式
- 读写文件
- 错误和异常
- 语法错误
- 异常
- 处理异常
- 抛出异常
- 用户自定义异常
- 定义清理操作
- 预定义的清理操作
- 类
- 名称和对象
- Python 作用域和命名空间
- 初探类
- 补充说明
- 继承
- 私有变量
- 杂项说明
- 迭代器
- 生成器
- 生成器表达式
- 标准库简介
- 操作系统接口
- 文件通配符
- 命令行参数
- 错误输出重定向和程序终止
- 字符串模式匹配
- 数学
- 互联网访问
- 日期和时间
- 数据压缩
- 性能测量
- 质量控制
- 自带电池
- 标准库简介 —— 第二部分
- 格式化输出
- 模板
- 使用二进制数据记录格式
- 多线程
- 日志
- 弱引用
- 用于操作列表的工具
- 十进制浮点运算
- 虚拟环境和包
- 概述
- 创建虚拟环境
- 使用pip管理包
- 接下来?
- 交互式编辑和编辑历史
- Tab 补全和编辑历史
- 默认交互式解释器的替代品
- 浮点算术:争议和限制
- 表示性错误
- 附录
- 交互模式
- 安装和使用 Python
- 命令行与环境
- 命令行
- 环境变量
- 在Unix平台中使用Python
- 获取最新版本的Python
- 构建Python
- 与Python相关的路径和文件
- 杂项
- 编辑器和集成开发环境
- 在Windows上使用 Python
- 完整安装程序
- Microsoft Store包
- nuget.org 安装包
- 可嵌入的包
- 替代捆绑包
- 配置Python
- 适用于Windows的Python启动器
- 查找模块
- 附加模块
- 在Windows上编译Python
- 其他平台
- 在苹果系统上使用 Python
- 获取和安装 MacPython
- IDE
- 安装额外的 Python 包
- Mac 上的图形界面编程
- 在 Mac 上分发 Python 应用程序
- 其他资源
- Python 语言参考
- 概述
- 其他实现
- 标注
- 词法分析
- 行结构
- 其他形符
- 标识符和关键字
- 字面值
- 运算符
- 分隔符
- 数据模型
- 对象、值与类型
- 标准类型层级结构
- 特殊方法名称
- 协程
- 执行模型
- 程序的结构
- 命名与绑定
- 异常
- 导入系统
- importlib
- 包
- 搜索
- 加载
- 基于路径的查找器
- 替换标准导入系统
- Package Relative Imports
- 有关 main 的特殊事项
- 开放问题项
- 参考文献
- 表达式
- 算术转换
- 原子
- 原型
- await 表达式
- 幂运算符
- 一元算术和位运算
- 二元算术运算符
- 移位运算
- 二元位运算
- 比较运算
- 布尔运算
- 条件表达式
- lambda 表达式
- 表达式列表
- 求值顺序
- 运算符优先级
- 简单语句
- 表达式语句
- 赋值语句
- assert 语句
- pass 语句
- del 语句
- return 语句
- yield 语句
- raise 语句
- break 语句
- continue 语句
- import 语句
- global 语句
- nonlocal 语句
- 复合语句
- if 语句
- while 语句
- for 语句
- try 语句
- with 语句
- 函数定义
- 类定义
- 协程
- 最高层级组件
- 完整的 Python 程序
- 文件输入
- 交互式输入
- 表达式输入
- 完整的语法规范
- Python 标准库
- 概述
- 可用性注释
- 内置函数
- 内置常量
- 由 site 模块添加的常量
- 内置类型
- 逻辑值检测
- 布尔运算 — and, or, not
- 比较
- 数字类型 — int, float, complex
- 迭代器类型
- 序列类型 — list, tuple, range
- 文本序列类型 — str
- 二进制序列类型 — bytes, bytearray, memoryview
- 集合类型 — set, frozenset
- 映射类型 — dict
- 上下文管理器类型
- 其他内置类型
- 特殊属性
- 内置异常
- 基类
- 具体异常
- 警告
- 异常层次结构
- 文本处理服务
- string — 常见的字符串操作
- re — 正则表达式操作
- 模块 difflib 是一个计算差异的助手
- textwrap — Text wrapping and filling
- unicodedata — Unicode 数据库
- stringprep — Internet String Preparation
- readline — GNU readline interface
- rlcompleter — GNU readline的完成函数
- 二进制数据服务
- struct — Interpret bytes as packed binary data
- codecs — Codec registry and base classes
- 数据类型
- datetime — 基础日期/时间数据类型
- calendar — General calendar-related functions
- collections — 容器数据类型
- collections.abc — 容器的抽象基类
- heapq — 堆队列算法
- bisect — Array bisection algorithm
- array — Efficient arrays of numeric values
- weakref — 弱引用
- types — Dynamic type creation and names for built-in types
- copy — 浅层 (shallow) 和深层 (deep) 复制操作
- pprint — 数据美化输出
- reprlib — Alternate repr() implementation
- enum — Support for enumerations
- 数字和数学模块
- numbers — 数字的抽象基类
- math — 数学函数
- cmath — Mathematical functions for complex numbers
- decimal — 十进制定点和浮点运算
- fractions — 分数
- random — 生成伪随机数
- statistics — Mathematical statistics functions
- 函数式编程模块
- itertools — 为高效循环而创建迭代器的函数
- functools — 高阶函数和可调用对象上的操作
- operator — 标准运算符替代函数
- 文件和目录访问
- pathlib — 面向对象的文件系统路径
- os.path — 常见路径操作
- fileinput — Iterate over lines from multiple input streams
- stat — Interpreting stat() results
- filecmp — File and Directory Comparisons
- tempfile — Generate temporary files and directories
- glob — Unix style pathname pattern expansion
- fnmatch — Unix filename pattern matching
- linecache — Random access to text lines
- shutil — High-level file operations
- macpath — Mac OS 9 路径操作函数
- 数据持久化
- pickle —— Python 对象序列化
- copyreg — Register pickle support functions
- shelve — Python object persistence
- marshal — Internal Python object serialization
- dbm — Interfaces to Unix “databases”
- sqlite3 — SQLite 数据库 DB-API 2.0 接口模块
- 数据压缩和存档
- zlib — 与 gzip 兼容的压缩
- gzip — 对 gzip 格式的支持
- bz2 — 对 bzip2 压缩算法的支持
- lzma — 用 LZMA 算法压缩
- zipfile — 在 ZIP 归档中工作
- tarfile — Read and write tar archive files
- 文件格式
- csv — CSV 文件读写
- configparser — Configuration file parser
- netrc — netrc file processing
- xdrlib — Encode and decode XDR data
- plistlib — Generate and parse Mac OS X .plist files
- 加密服务
- hashlib — 安全哈希与消息摘要
- hmac — 基于密钥的消息验证
- secrets — Generate secure random numbers for managing secrets
- 通用操作系统服务
- os — 操作系统接口模块
- io — 处理流的核心工具
- time — 时间的访问和转换
- argparse — 命令行选项、参数和子命令解析器
- getopt — C-style parser for command line options
- 模块 logging — Python 的日志记录工具
- logging.config — 日志记录配置
- logging.handlers — Logging handlers
- getpass — 便携式密码输入工具
- curses — 终端字符单元显示的处理
- curses.textpad — Text input widget for curses programs
- curses.ascii — Utilities for ASCII characters
- curses.panel — A panel stack extension for curses
- platform — Access to underlying platform's identifying data
- errno — Standard errno system symbols
- ctypes — Python 的外部函数库
- 并发执行
- threading — 基于线程的并行
- multiprocessing — 基于进程的并行
- concurrent 包
- concurrent.futures — 启动并行任务
- subprocess — 子进程管理
- sched — 事件调度器
- queue — 一个同步的队列类
- _thread — 底层多线程 API
- _dummy_thread — _thread 的替代模块
- dummy_threading — 可直接替代 threading 模块。
- contextvars — Context Variables
- Context Variables
- Manual Context Management
- asyncio support
- 网络和进程间通信
- asyncio — 异步 I/O
- socket — 底层网络接口
- ssl — TLS/SSL wrapper for socket objects
- select — Waiting for I/O completion
- selectors — 高级 I/O 复用库
- asyncore — 异步socket处理器
- asynchat — 异步 socket 指令/响应 处理器
- signal — Set handlers for asynchronous events
- mmap — Memory-mapped file support
- 互联网数据处理
- email — 电子邮件与 MIME 处理包
- json — JSON 编码和解码器
- mailcap — Mailcap file handling
- mailbox — Manipulate mailboxes in various formats
- mimetypes — Map filenames to MIME types
- base64 — Base16, Base32, Base64, Base85 数据编码
- binhex — 对binhex4文件进行编码和解码
- binascii — 二进制和 ASCII 码互转
- quopri — Encode and decode MIME quoted-printable data
- uu — Encode and decode uuencode files
- 结构化标记处理工具
- html — 超文本标记语言支持
- html.parser — 简单的 HTML 和 XHTML 解析器
- html.entities — HTML 一般实体的定义
- XML处理模块
- xml.etree.ElementTree — The ElementTree XML API
- xml.dom — The Document Object Model API
- xml.dom.minidom — Minimal DOM implementation
- xml.dom.pulldom — Support for building partial DOM trees
- xml.sax — Support for SAX2 parsers
- xml.sax.handler — Base classes for SAX handlers
- xml.sax.saxutils — SAX Utilities
- xml.sax.xmlreader — Interface for XML parsers
- xml.parsers.expat — Fast XML parsing using Expat
- 互联网协议和支持
- webbrowser — 方便的Web浏览器控制器
- cgi — Common Gateway Interface support
- cgitb — Traceback manager for CGI scripts
- wsgiref — WSGI Utilities and Reference Implementation
- urllib — URL 处理模块
- urllib.request — 用于打开 URL 的可扩展库
- urllib.response — Response classes used by urllib
- urllib.parse — Parse URLs into components
- urllib.error — Exception classes raised by urllib.request
- urllib.robotparser — Parser for robots.txt
- http — HTTP 模块
- http.client — HTTP协议客户端
- ftplib — FTP protocol client
- poplib — POP3 protocol client
- imaplib — IMAP4 protocol client
- nntplib — NNTP protocol client
- smtplib —SMTP协议客户端
- smtpd — SMTP Server
- telnetlib — Telnet client
- uuid — UUID objects according to RFC 4122
- socketserver — A framework for network servers
- http.server — HTTP 服务器
- http.cookies — HTTP state management
- http.cookiejar — Cookie handling for HTTP clients
- xmlrpc — XMLRPC 服务端与客户端模块
- xmlrpc.client — XML-RPC client access
- xmlrpc.server — Basic XML-RPC servers
- ipaddress — IPv4/IPv6 manipulation library
- 多媒体服务
- audioop — Manipulate raw audio data
- aifc — Read and write AIFF and AIFC files
- sunau — 读写 Sun AU 文件
- wave — 读写WAV格式文件
- chunk — Read IFF chunked data
- colorsys — Conversions between color systems
- imghdr — 推测图像类型
- sndhdr — 推测声音文件的类型
- ossaudiodev — Access to OSS-compatible audio devices
- 国际化
- gettext — 多语种国际化服务
- locale — 国际化服务
- 程序框架
- turtle — 海龟绘图
- cmd — 支持面向行的命令解释器
- shlex — Simple lexical analysis
- Tk图形用户界面(GUI)
- tkinter — Tcl/Tk的Python接口
- tkinter.ttk — Tk themed widgets
- tkinter.tix — Extension widgets for Tk
- tkinter.scrolledtext — 滚动文字控件
- IDLE
- 其他图形用户界面(GUI)包
- 开发工具
- typing — 类型标注支持
- pydoc — Documentation generator and online help system
- doctest — Test interactive Python examples
- unittest — 单元测试框架
- unittest.mock — mock object library
- unittest.mock 上手指南
- 2to3 - 自动将 Python 2 代码转为 Python 3 代码
- test — Regression tests package for Python
- test.support — Utilities for the Python test suite
- test.support.script_helper — Utilities for the Python execution tests
- 调试和分析
- bdb — Debugger framework
- faulthandler — Dump the Python traceback
- pdb — The Python Debugger
- The Python Profilers
- timeit — 测量小代码片段的执行时间
- trace — Trace or track Python statement execution
- tracemalloc — Trace memory allocations
- 软件打包和分发
- distutils — 构建和安装 Python 模块
- ensurepip — Bootstrapping the pip installer
- venv — 创建虚拟环境
- zipapp — Manage executable Python zip archives
- Python运行时服务
- sys — 系统相关的参数和函数
- sysconfig — Provide access to Python's configuration information
- builtins — 内建对象
- main — 顶层脚本环境
- warnings — Warning control
- dataclasses — 数据类
- contextlib — Utilities for with-statement contexts
- abc — 抽象基类
- atexit — 退出处理器
- traceback — Print or retrieve a stack traceback
- future — Future 语句定义
- gc — 垃圾回收器接口
- inspect — 检查对象
- site — Site-specific configuration hook
- 自定义 Python 解释器
- code — Interpreter base classes
- codeop — Compile Python code
- 导入模块
- zipimport — Import modules from Zip archives
- pkgutil — Package extension utility
- modulefinder — 查找脚本使用的模块
- runpy — Locating and executing Python modules
- importlib — The implementation of import
- Python 语言服务
- parser — Access Python parse trees
- ast — 抽象语法树
- symtable — Access to the compiler's symbol tables
- symbol — 与 Python 解析树一起使用的常量
- token — 与Python解析树一起使用的常量
- keyword — 检验Python关键字
- tokenize — Tokenizer for Python source
- tabnanny — 模糊缩进检测
- pyclbr — Python class browser support
- py_compile — Compile Python source files
- compileall — Byte-compile Python libraries
- dis — Python 字节码反汇编器
- pickletools — Tools for pickle developers
- 杂项服务
- formatter — Generic output formatting
- Windows系统相关模块
- msilib — Read and write Microsoft Installer files
- msvcrt — Useful routines from the MS VC++ runtime
- winreg — Windows 注册表访问
- winsound — Sound-playing interface for Windows
- Unix 专有服务
- posix — The most common POSIX system calls
- pwd — 用户密码数据库
- spwd — The shadow password database
- grp — The group database
- crypt — Function to check Unix passwords
- termios — POSIX style tty control
- tty — 终端控制功能
- pty — Pseudo-terminal utilities
- fcntl — The fcntl and ioctl system calls
- pipes — Interface to shell pipelines
- resource — Resource usage information
- nis — Interface to Sun's NIS (Yellow Pages)
- Unix syslog 库例程
- 被取代的模块
- optparse — Parser for command line options
- imp — Access the import internals
- 未创建文档的模块
- 平台特定模块
- 扩展和嵌入 Python 解释器
- 推荐的第三方工具
- 不使用第三方工具创建扩展
- 使用 C 或 C++ 扩展 Python
- 自定义扩展类型:教程
- 定义扩展类型:已分类主题
- 构建C/C++扩展
- 在Windows平台编译C和C++扩展
- 在更大的应用程序中嵌入 CPython 运行时
- Embedding Python in Another Application
- Python/C API 参考手册
- 概述
- 代码标准
- 包含文件
- 有用的宏
- 对象、类型和引用计数
- 异常
- 嵌入Python
- 调试构建
- 稳定的应用程序二进制接口
- The Very High Level Layer
- Reference Counting
- 异常处理
- Printing and clearing
- 抛出异常
- Issuing warnings
- Querying the error indicator
- Signal Handling
- Exception Classes
- Exception Objects
- Unicode Exception Objects
- Recursion Control
- 标准异常
- 标准警告类别
- 工具
- 操作系统实用程序
- 系统功能
- 过程控制
- 导入模块
- Data marshalling support
- 语句解释及变量编译
- 字符串转换与格式化
- 反射
- 编解码器注册与支持功能
- 抽象对象层
- Object Protocol
- 数字协议
- Sequence Protocol
- Mapping Protocol
- 迭代器协议
- 缓冲协议
- Old Buffer Protocol
- 具体的对象层
- 基本对象
- 数值对象
- 序列对象
- 容器对象
- 函数对象
- 其他对象
- Initialization, Finalization, and Threads
- 在Python初始化之前
- 全局配置变量
- Initializing and finalizing the interpreter
- Process-wide parameters
- Thread State and the Global Interpreter Lock
- Sub-interpreter support
- Asynchronous Notifications
- Profiling and Tracing
- Advanced Debugger Support
- Thread Local Storage Support
- 内存管理
- 概述
- 原始内存接口
- Memory Interface
- 对象分配器
- 默认内存分配器
- Customize Memory Allocators
- The pymalloc allocator
- tracemalloc C API
- 示例
- 对象实现支持
- 在堆中分配对象
- Common Object Structures
- Type 对象
- Number Object Structures
- Mapping Object Structures
- Sequence Object Structures
- Buffer Object Structures
- Async Object Structures
- 使对象类型支持循环垃圾回收
- API 和 ABI 版本管理
- 分发 Python 模块
- 关键术语
- 开源许可与协作
- 安装工具
- 阅读指南
- 我该如何...?
- ...为我的项目选择一个名字?
- ...创建和分发二进制扩展?
- 安装 Python 模块
- 关键术语
- 基本使用
- 我应如何 ...?
- ... 在 Python 3.4 之前的 Python 版本中安装 pip ?
- ... 只为当前用户安装软件包?
- ... 安装科学计算类 Python 软件包?
- ... 使用并行安装的多个 Python 版本?
- 常见的安装问题
- 在 Linux 的系统 Python 版本上安装
- 未安装 pip
- 安装二进制编译扩展
- Python 常用指引
- 将 Python 2 代码迁移到 Python 3
- 简要说明
- 详情
- 将扩展模块移植到 Python 3
- 条件编译
- 对象API的更改
- 模块初始化和状态
- CObject 替换为 Capsule
- 其他选项
- Curses Programming with Python
- What is curses?
- Starting and ending a curses application
- Windows and Pads
- Displaying Text
- User Input
- For More Information
- 实现描述器
- 摘要
- 定义和简介
- 描述器协议
- 发起调用描述符
- 描述符示例
- Properties
- 函数和方法
- Static Methods and Class Methods
- 函数式编程指引
- 概述
- 迭代器
- 生成器表达式和列表推导式
- 生成器
- 内置函数
- itertools 模块
- The functools module
- Small functions and the lambda expression
- Revision History and Acknowledgements
- 引用文献
- 日志 HOWTO
- 日志基础教程
- 进阶日志教程
- 日志级别
- 有用的处理程序
- 记录日志中引发的异常
- 使用任意对象作为消息
- 优化
- 日志操作手册
- 在多个模块中使用日志
- 在多线程中使用日志
- 使用多个日志处理器和多种格式化
- 在多个地方记录日志
- 日志服务器配置示例
- 处理日志处理器的阻塞
- Sending and receiving logging events across a network
- Adding contextual information to your logging output
- Logging to a single file from multiple processes
- Using file rotation
- Use of alternative formatting styles
- Customizing LogRecord
- Subclassing QueueHandler - a ZeroMQ example
- Subclassing QueueListener - a ZeroMQ example
- An example dictionary-based configuration
- Using a rotator and namer to customize log rotation processing
- A more elaborate multiprocessing example
- Inserting a BOM into messages sent to a SysLogHandler
- Implementing structured logging
- Customizing handlers with dictConfig()
- Using particular formatting styles throughout your application
- Configuring filters with dictConfig()
- Customized exception formatting
- Speaking logging messages
- Buffering logging messages and outputting them conditionally
- Formatting times using UTC (GMT) via configuration
- Using a context manager for selective logging
- 正则表达式HOWTO
- 概述
- 简单模式
- 使用正则表达式
- 更多模式能力
- 修改字符串
- 常见问题
- 反馈
- 套接字编程指南
- 套接字
- 创建套接字
- 使用一个套接字
- 断开连接
- 非阻塞的套接字
- 排序指南
- 基本排序
- 关键函数
- Operator 模块函数
- 升序和降序
- 排序稳定性和排序复杂度
- 使用装饰-排序-去装饰的旧方法
- 使用 cmp 参数的旧方法
- 其它
- Unicode 指南
- Unicode 概述
- Python's Unicode Support
- Reading and Writing Unicode Data
- Acknowledgements
- 如何使用urllib包获取网络资源
- 概述
- Fetching URLs
- 处理异常
- info and geturl
- Openers and Handlers
- Basic Authentication
- Proxies
- Sockets and Layers
- 脚注
- Argparse 教程
- 概念
- 基础
- 位置参数介绍
- Introducing Optional arguments
- Combining Positional and Optional arguments
- Getting a little more advanced
- Conclusion
- ipaddress模块介绍
- 创建 Address/Network/Interface 对象
- 审查 Address/Network/Interface 对象
- Network 作为 Address 列表
- 比较
- 将IP地址与其他模块一起使用
- 实例创建失败时获取更多详细信息
- Argument Clinic How-To
- The Goals Of Argument Clinic
- Basic Concepts And Usage
- Converting Your First Function
- Advanced Topics
- 使用 DTrace 和 SystemTap 检测CPython
- Enabling the static markers
- Static DTrace probes
- Static SystemTap markers
- Available static markers
- SystemTap Tapsets
- 示例
- Python 常见问题
- Python常见问题
- 一般信息
- 现实世界中的 Python
- 编程常见问题
- 一般问题
- 核心语言
- 数字和字符串
- 性能
- 序列(元组/列表)
- 对象
- 模块
- 设计和历史常见问题
- 为什么Python使用缩进来分组语句?
- 为什么简单的算术运算得到奇怪的结果?
- 为什么浮点计算不准确?
- 为什么Python字符串是不可变的?
- 为什么必须在方法定义和调用中显式使用“self”?
- 为什么不能在表达式中赋值?
- 为什么Python对某些功能(例如list.index())使用方法来实现,而其他功能(例如len(List))使用函数实现?
- 为什么 join()是一个字符串方法而不是列表或元组方法?
- 异常有多快?
- 为什么Python中没有switch或case语句?
- 难道不能在解释器中模拟线程,而非得依赖特定于操作系统的线程实现吗?
- 为什么lambda表达式不能包含语句?
- 可以将Python编译为机器代码,C或其他语言吗?
- Python如何管理内存?
- 为什么CPython不使用更传统的垃圾回收方案?
- CPython退出时为什么不释放所有内存?
- 为什么有单独的元组和列表数据类型?
- 列表是如何在CPython中实现的?
- 字典是如何在CPython中实现的?
- 为什么字典key必须是不可变的?
- 为什么 list.sort() 没有返回排序列表?
- 如何在Python中指定和实施接口规范?
- 为什么没有goto?
- 为什么原始字符串(r-strings)不能以反斜杠结尾?
- 为什么Python没有属性赋值的“with”语句?
- 为什么 if/while/def/class语句需要冒号?
- 为什么Python在列表和元组的末尾允许使用逗号?
- 代码库和插件 FAQ
- 通用的代码库问题
- 通用任务
- 线程相关
- 输入输出
- 网络 / Internet 编程
- 数据库
- 数学和数字
- 扩展/嵌入常见问题
- 可以使用C语言中创建自己的函数吗?
- 可以使用C++语言中创建自己的函数吗?
- C很难写,有没有其他选择?
- 如何从C执行任意Python语句?
- 如何从C中评估任意Python表达式?
- 如何从Python对象中提取C的值?
- 如何使用Py_BuildValue()创建任意长度的元组?
- 如何从C调用对象的方法?
- 如何捕获PyErr_Print()(或打印到stdout / stderr的任何内容)的输出?
- 如何从C访问用Python编写的模块?
- 如何从Python接口到C ++对象?
- 我使用Setup文件添加了一个模块,为什么make失败了?
- 如何调试扩展?
- 我想在Linux系统上编译一个Python模块,但是缺少一些文件。为什么?
- 如何区分“输入不完整”和“输入无效”?
- 如何找到未定义的g++符号__builtin_new或__pure_virtual?
- 能否创建一个对象类,其中部分方法在C中实现,而其他方法在Python中实现(例如通过继承)?
- Python在Windows上的常见问题
- 我怎样在Windows下运行一个Python程序?
- 我怎么让 Python 脚本可执行?
- 为什么有时候 Python 程序会启动缓慢?
- 我怎样使用Python脚本制作可执行文件?
- *.pyd 文件和DLL文件相同吗?
- 我怎样将Python嵌入一个Windows程序?
- 如何让编辑器不要在我的 Python 源代码中插入 tab ?
- 如何在不阻塞的情况下检查按键?
- 图形用户界面(GUI)常见问题
- 图形界面常见问题
- Python 是否有平台无关的图形界面工具包?
- 有哪些Python的GUI工具是某个平台专用的?
- 有关Tkinter的问题
- “为什么我的电脑上安装了 Python ?”
- 什么是Python?
- 为什么我的电脑上安装了 Python ?
- 我能删除 Python 吗?
- 术语对照表
- 文档说明
- Python 文档贡献者
- 解决 Bug
- 文档错误
- 使用 Python 的错误追踪系统
- 开始为 Python 贡献您的知识
- 版权
- 历史和许可证
- 软件历史
- 访问Python或以其他方式使用Python的条款和条件
- Python 3.7.3 的 PSF 许可协议
- Python 2.0 的 BeOpen.com 许可协议
- Python 1.6.1 的 CNRI 许可协议
- Python 0.9.0 至 1.2 的 CWI 许可协议
- 集成软件的许可和认可
- Mersenne Twister
- 套接字
- Asynchronous socket services
- Cookie management
- Execution tracing
- UUencode and UUdecode functions
- XML Remote Procedure Calls
- test_epoll
- Select kqueue
- SipHash24
- strtod and dtoa
- OpenSSL
- expat
- libffi
- zlib
- cfuhash
- libmpdec