### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](select.xhtml "select --- Waiting for I/O completion") |
- [上一頁](socket.xhtml "socket --- 底層網絡接口") |
- 
- [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 --- 底層網絡接口") |
- 
- [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