Https Connection Python

HTTPS connection Python

Python 2.x: docs.python.org/2/library/httplib.html:

Note: HTTPS support is only available if the socket module was compiled with SSL support.

Python 3.x: docs.python.org/3/library/http.client.html:

Note HTTPS support is only available if Python was compiled with SSL support (through the ssl module).

#!/usr/bin/env python

import httplib
c = httplib.HTTPSConnection("ccc.de")
c.request("GET", "/")
response = c.getresponse()
print response.status, response.reason
data = response.read()
print data
# =>
# 200 OK
# <!DOCTYPE html ....

To verify if SSL is enabled, try:

>>> import socket
>>> socket.ssl
<function ssl at 0x4038b0>

Opening a SSL socket connection in Python

Ok, I figured out what was wrong. It was kind of foolish of me. I had two problems with my code. My first mistake was when specifying the ssl_version I put in TLSv1 when it should have been ssl.PROTOCOL_TLSv1. The second mistake was that I wasn't referencing the wrapped socket, instead I was calling the original socket that I have created. The below code seemed to work for me.

import socket
import ssl

# SET VARIABLES
packet, reply = "<packet>SOME_DATA</packet>", ""
HOST, PORT = 'XX.XX.XX.XX', 4434

# CREATE SOCKET
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)

# WRAP SOCKET
wrappedSocket = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_TLSv1, ciphers="ADH-AES256-SHA")

# CONNECT AND PRINT REPLY
wrappedSocket.connect((HOST, PORT))
wrappedSocket.send(packet)
print wrappedSocket.recv(1280)

# CLOSE SOCKET CONNECTION
wrappedSocket.close()

Hope this can help somebody!

HTTPS connection using PEM Certificate

See http://docs.python.org/library/httplib.html

httplib.HTTPSConnection does not do any verification of the server’s certificate.

The option to include your private certificate is when the server is doing certificate based authentication of clients. I.e. the server is checking the client has a certificate signed by a CA that it trusts and is allowed to access it's resources.


If you don't specify the cert optional argument, you should be able to connect to the HTTPS server, but not validate the server certificate.


Update

Following your comment that you've tried basic auth, it looks like the server still wants you to authenticate using basic auth. Either your credentials are invalid (have you independently verified them?) or your Authenticate header isn't formatted correctly. Modifying your example code to include a basic auth header and an empty post payload:

import httplib  
conn = httplib.HTTPSConnection('10.10.10.10','443')
auth_header = 'Basic %s' % (":".join(["myusername","mypassword"]).encode('Base64').strip('\r\n'))
conn.request("POST", "/","",{'Authorization':auth_header})
response = conn.getresponse()
print response.status, response.reason
conn.close()

Python: How to handle https connection refused error and write the logs in server

TL;DR

If you want to avoid During handling of the above exception, another exception occurred catch the first exception from your trace.


Your exception handling is correct it's just that you aren't catching all of them :)

In general it is okay to do that, catch exceptions which you want to handle differently otherwise just raise/handle it commonly.


Your Code:

I am getting a socket error which then raises a ConnectionError, in order to fix that add the socket error as the first exception you expect:

def GetPost(data):
logging.info('-----------GetPost Function Starts Here-----------')
try:
headers = {
'user-agent': 'customize header string',
'Content-Type': 'application/json; charset=utf-8'
}
response = requests.post('http://dummyurl.org', data= data, headers=headers, timeout=3)
logging.info('Http received response code: ', response.status_code)
response.raise_for_status()
except socket.error as exc:
logging.error(f"Caught exception socket.error : {exc}")
except requests.exceptions.HTTPError as httpErr:
logging.error("Http Error: ", exc_info=httpErr)
except requests.exceptions.ConnectionError as connErr:
logging.error("Error Connecting: ", exc_info=connErr)
except requests.exceptions.Timeout as timeOutErr:
logging.error("Timeout Error: ", exc_info=timeOutErr)
except requests.exceptions.RequestException as reqErr:
logging.error("Something Else: ", exc_info=reqErr)
except Exception as err:
raise RuntimeError(f"Something bad happened {err}") from None
logging.info('-----------GetPost Function Ends Here-----------')

GetPost(data)

Refer: Handling Exceptions

Setting newer ssl version in python http.client.HTTPSConnection

... it worked when i used ... curl ..."http://192.168.11.1:444/post"

What you are successfully doing with curl is a plain HTTP request (http://... not https://...). What you are trying (and failing) with your code is a HTTPS request, i.e. HTTP over TLS. The error message is the result of attempting to speak TLS against a server which does not support TLS.



Related Topics



Leave a reply



Submit