How can I retrieve the TLS/SSL peer certificate of a remote host using python?

前端 未结 4 1239
难免孤独
难免孤独 2020-11-30 22:52

I need to scan through a list of IPs and retrieve the common name from the certificate on that IP (for every IP that allows port 443 connections). I have been able to succes

4条回答
  •  鱼传尺愫
    2020-11-30 23:51

    On Mac you need to install swig and M2Crypto

    On terminal run:

    brew install swig
    

    And then:

    sudo pip install m2crypto
    

    Then you can run the code above:

    from socket import socket
    import ssl
    import M2Crypto
    import OpenSSL
    
    # M2Crypto
    cert = ssl.get_server_certificate(('www.google.com', 443))
    x509 = M2Crypto.X509.load_cert_string(cert)
    print x509.get_subject().as_text()
    # 'C=US, ST=California, L=Mountain View, O=Google Inc, CN=www.google.com'
    
    # OpenSSL
    x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
    print x509.get_subject().get_components()
    #[('C', 'US'),
    # ('ST', 'California'),
    # ('L', 'Mountain View'),
    # ('O', 'Google Inc'),
    # ('CN', 'www.google.com')]
    

提交回复
热议问题