如何在python请求传递证书的情况下登录到cgi?

2024-05-14 21:17:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python中的requests模块来处理cgi-bin来登录网站,但是我必须使用数字证书file.pfx来登录

我正在使用我找到的代码https://gist.github.com/erikbern/756b1d8df2d1487497d29b90e81f8068

@contextlib.contextmanager
def pfx_to_pem(pfx_path, pfx_password):
    ''' Decrypts the .pfx file to be used with requests. '''
    with tempfile.NamedTemporaryFile(suffix='.pem') as t_pem:
        f_pem = open(t_pem.name, 'wb')
        pfx = open(pfx_path, 'rb').read()
        p12 = OpenSSL.crypto.load_pkcs12(pfx, pfx_password)
        f_pem.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, p12.get_privatekey()))
        f_pem.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, p12.get_certificate()))
        ca = p12.get_ca_certificates()
        if ca is not None:
            for cert in ca:
                f_pem.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert))
        f_pem.close()
        yield t_pem.name

    with pfx_to_pem('path/file.pfx', 'password') as cert:
    login_page = "https://zeusr.sii.cl/AUT2000/InicioAutenticacion/IngresoCertificado.html?https://misiir.sii.cl/cgi_misii/siihome.cgi"

    headers = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "es-ES,es;q=0.9",
        "Cache-Control": "max-age=0",
        "Connection": "keep-alive",
        "Cookie": "s_cc=true",
        "Host": "herculesr.sii.cl",
        "Origin": "https://zeusr.sii.cl",
        "Referer": "https://misiir.sii.cl/cgi_misii/siihome.cgi",  
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "same-site",
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36"
    }

    s = requests.Session()
    s.cert = cert
    print(s.cert)
    r = s.get(login_page, cert=s.cert, headers=headers)
    print(r.content)

当我用收到的邮件头发送邮件时 b'Error 400' 如果没有标题,我收到的html文档中有一条我没有记录的消息


Tags: tohttpsgetcertclcryptorequestspem
1条回答
网友
1楼 · 发布于 2024-05-14 21:17:55

最后,我必须将.pfx文件转换为cert和key,并且工作起来很容易,只是在请求中我必须添加verify=false

s = requests.Session()
s.cert = cert
r = s.get(login_page, cert=("certificate.cert", "certkey.key"), verify=false)
print(r.content)

相关问题 更多 >

    热门问题