windows - 如何使用 cacert 文件在 Powershell (Invoke-WebRequest) 中执行等效的 cUrl?

标签 windows powershell curl

基本上我想将命令 curl 翻译为与当前在 linux 服务器中相同的参数,但在 Powershell 中,以便上传文件:

curl -v -T $file -u user:password http://myurl --cacert /opt/keystores/ca_cert.pem

我找到了执行此任务的等效命令:PowerShell 3.0+ 的“Invoke-WebRequest”,但问题是我不知道如何使用 CA 证书文件 (.pem) 调用它,而且我还没有'在互联网上找到任何样本。

谢谢!

最佳答案

当您在 .NET 中建立 TLS 连接时,将根据 RemoteCertificateValidationCallback function 验证对等证书,由相关 AppDomain 的 ServicePointManager 管理。

大多数关于如何在 PowerShell 中覆盖默认验证的示例都会告诉您只需执行以下操作:

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

不要那样做! - 它会完全绕过验证。

可以做的是实现适当的回调函数并手动调用链验证。在执行此操作之前,您可以将不在机器或用户证书存储中的证书添加到您可以验证的链列表中:

$callback = {
    param(
        $sender,
        [System.Security.Cryptography.X509Certificates.X509Certificate]$certificate,
        [System.Security.Cryptography.X509Certificates.X509Chain]$chain,
        [System.Net.Security.SslPolicyErrors]$sslPolicyErrors
    )

    # No need to retype this long type name
    $CertificateType = [System.Security.Cryptography.X509Certificates.X509Certificate2]

    # Read the CA cert from file
    $CACert = $CertificateType::CreateFromCertFile("C:\path\to\ca.crt") -as $CertificateType

    # Add the CA cert from the file to the ExtraStore on the Chain object
    $null = $chain.ChainPolicy.ExtraStore.Add($CACert)

    # return the result of chain validation
    return $chain.Build($certificate)
}

# Assign your delegate to the ServicePointManager callback
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = $callback

# Do your Invoke-WebRequest or WebClient call here

我不知道如何从一个 PEM 文件中读取多个证书到一个证书集合中,所以你必须一个一个地添加每个 ca 证书,抱歉

关于windows - 如何使用 cacert 文件在 Powershell (Invoke-WebRequest) 中执行等效的 cUrl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36722870/

相关文章:

windows - 找到具有搜索功能的文件,但在批处理文件中没有删除功能?

arrays - Powershell:有没有一种方法可以将数组中的变量作为字符串添加到文件中?

xml - 使用Powershell XMLReader读取xml文件而不锁定xml文件

javascript - 使用 JavaScript 功能获取命令行 URL

使用 libcurl 固定 SSL 证书

c - 如何在一个窗口上显示超过50个按钮?

c++ - 使用 "::"字符串名称在 C++ 中调用 DLL 导出

windows - Perl 包问题

Powershell:展开存档:无法验证参数 'Path' 上的参数

java - 将 Curl 转换为 Java 的 POST api