Navigation

home code debian images resume weblog wiki

Older news:

Dec 11, 2006:

Debian GNU/Linux

About lychnis.net
Jul 7, 2005:
Wanneer gebruik je -d en wanneer gebruik je -t?
Feb 18, 2005:
Mixing whitespace
Jan 10, 2005:
The difference between dogs and cats
Dec 22, 2004:
Sunrise in winter
Dec 12, 2004:
New site layout

Browse:


python-gnutls/meta

Posted on 2004-01-25 by ivo :: /meta :: link

python-gnutls provides a set of bindings so that the GnuTLS library can be used from your python programs. This enables you to create secure internet sockets, that can serve on either the server or client side of a connection.

Announcements regarding python-gnutls—information about new releases, including change logs—are made in a section on programming in my weblog: python-gnutls. See that page for the latest release.

For more about GnuTLS, please see their website.


It's very simple to create a secure client socket, it's just two more calls after your socket is ready. The following example is a simple relay between the terminal (stdin/stdout) and a remote host.

import gnutls
import socket
import select
import os

def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('some-imap-host', some-port))
    c = gnutls.client(s)
    c.handshake()

    ins = os.fdopen(0, "r", 0)

    loop = True
    while loop:
        readers, writers, errors = select.select([ins, s], [], [])

        if len(readers):
            for r in readers:
                if r == ins:
                    text = ins.read(1)
                    if text:
                        c.send(text)
                    else:
                        c.shutdown(gnutls.SHUT_WR)
                        loop = False
                else:
                    text = c.recv(1000)
                    if text:
                        sys.stdout.write(text)
                    else:
                        loop = False

    del c
    s.close()


if __name__ == '__main__':
    main()

An example output, when communicating with an IMAPS server (lines wrapped for display purposes; blue text is typed in stdin):

> python simpleclient.py
* OK [CAPABILITY IMAP4rev1 CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT
    THREAD=REFERENCES SORT QUOTA AUTH=PLAIN] Courier-IMAP ready.
    Copyright 1998-2003 Double Precision, Inc.  See COPYING for
    distribution information.
A LOGOUT
* BYE Courier-IMAP server shutting down
A OK LOGOUT completed