Python SSL Tutorial

Written by kevin walker
  • Share
  • Tweet
  • Share
  • Email

Python is an interpreted language that has become popular with many programmers and server administrators. It is known for its relative ease-of-use and its sizeable library of tools to handle common computing tasks, ranging from graphics animation to networking. An example of this is the SSL library, which provides all the tools a developer needs to create a Secure Sockets Layer (SSL) for clients and servers.

Skill level:
Moderately Easy

Things you need

  • SSL library
  • SSL certificate and key (Optional)

Show MoreHide


  1. 1

    Open a text-editor, preferably a programming editor with Python syntax highlighting.

  2. 2

    Paste the following code into your editor, taken directly from the Python SSL library documentation:

    import socket, ssl, pprint

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    require a certificate from the server

    ssl_sock = ssl.wrap_socket(s,


    ssl_sock.connect(('', 443))


    note that closing the SSLSocket will also close the underlying socket


    This simple SSL client program will connect to a server (in this case,, request a copy of its SSL certificate, and print the information about it, before closing the connection. Save your work as ""

  3. 3

    Open a new text editor and paste the following SSL server code into it. Again, this code is taken directly from the SSL documentation:

    import socket, ssl

    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)

    context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")

    bindsocket = socket.socket()

    bindsocket.bind(('', 10023))


    while True:

    newsocket, fromaddr = bindsocket.accept()

    connstream = context.wrap_socket(newsocket, server_side=True)





    This code is slightly more complex, and it requires that you purchase an SSL certificate. These certificates cannot be program-generated. They must be created by a "trusted" certificate provider, such as Verisign. Certificates generally cost between £259 and £974 per year, though they can sometimes be purchased more cheaply in combination with web-hosting service contracts. If you have a certificate and its key, replace the "mycertfile" with the file name for your certificate and the "mykeyfile" with the file name for its key.

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.