Opening a SSL socket connection in Python

前端 未结 4 1867
予麋鹿
予麋鹿 2020-11-27 12:30

I\'m trying to establish a secure socket connection in Python, and i\'m having a hard time with the SSL bit of it. I\'ve found some code examples of how to establish a conn

4条回答
  •  一生所求
    2020-11-27 12:41

    I was looking for a good working ssl socket that starts the connection with a https package. This helped me a lot but is a little outdated, so here is the code for python3:

    import socket
    import ssl
    
    package = "GET /ws/LiveWebcastUpdate/22000557 HTTP/1.1\r\nHost: 
    www.website_name.com\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; 
    rv:80.0) Gecko/20100101 Firefox/80.0\r\nAccept: */*\r\nAccept-Language: nl,en- 
    US;q=0.7,en;q=0.3\r\nSec-WebSocket-Version: 13\r\nOrigin: 
    https://www.website_name.com\r\nSec-WebSocket-Key: 
    NU/EsJMICjSociJ751l0Xw==\r\nConnection: keep-alive, Upgrade\r\nPragma: no- 
    cache\r\nCache-Control: no-cache\r\nUpgrade: websocket\r\n\r\n"
    
    hostname = 'www.website_name.com'
    port = 443
    
    context = ssl.create_default_context()
    
    with socket.create_connection((hostname, port)) as sock:
        with context.wrap_socket(sock, server_hostname=hostname) as ssock:
            print(ssock.version())
            ssock.send(package.encode())
            while True:
                data = ssock.recv(2048)
                if ( len(data) < 1 ) :
                    break
                print(data)
    

    This is as simple as possible, for more information visit https://docs.python.org/3/library/ssl.html

    Kind regards,

    Okido (Niek Tuytel)

提交回复
热议问题