Advertisement
rfmonk

sslclient.py

Jan 25th, 2014
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.05 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. import os
  5. import socket
  6. import ssl
  7. import sys
  8. from backports.ssl_match_hostname import match_hostname, CertificateError
  9.  
  10. try:
  11.     script_name, hostname = sys.argv
  12. except ValueError:
  13.     print >>sys.stderr, 'usage: sslclient.py <hostname>'
  14.     sys.exit(2)
  15.  
  16. # First we connect, as usual, with a socket.
  17.  
  18. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  19. sock.connect((hostname, 443))
  20.  
  21. # Next, we turn the socket over to the SSL library
  22.  
  23. ca_certs_path = os.path.join(os.path.dirname(script_name), 'certfiles.crt')
  24. sslsock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_SSLv3,
  25.                           cert_reqs=ssl.CERT_REQUIRED,
  26.                           ca_certs=ca_certs_path)
  27.  
  28. # Does the cert match the hostname to which we are connecting?
  29.  
  30. try:
  31.     match_hostname(sslsock.getpeercert(), hostname)
  32. except CertificateError, ce:
  33.     print 'Certificate error:', str(ce)
  34.     sys.exit(1)
  35.  
  36. sslsock.sendall('GET / HTTP/1.0\r\n\r\n')
  37. result = sslsock.makefile().read()
  38. print 'The document https://%s/ is %d bytes long' % (hostname, len(result))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement