如何使用cacert文件在Powershell(Invoke-WebRequest)中执行等效的cUrl? [英] How to execute a cUrl equivalent in Powershell (Invoke-WebRequest) using cacert file?

查看:114
本文介绍了如何使用cacert文件在Powershell(Invoke-WebRequest)中执行等效的cUrl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Basically i would like to translate the command curl as with same parameters as its currently in a linux server, but in Powershell, in order to upload a file:

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

我找到了等效的命令来执行此任务:PowerShell 3.0+的 Invoke-WebRequest,但问题是我不知道如何调用它使用CA Cert文件(.pem),但我在Internet上找不到任何示例。

I've found a equivalent command to perform this task: "Invoke-WebRequest" for PowerShell 3.0+, but the problem is I don't know how to call it using a CA Cert file (.pem) and I haven't found any sample in Internet.

谢谢!

推荐答案

在.NET中建立 TLS 连接时,将根据 RemoteCertificateValidationCallback 函数,由有问题的AppDomain的 ServicePointManager 控制。

When you make a TLS connection in .NET, the peer certificate is validated against a RemoteCertificateValidationCallback function, governed by the ServicePointManager for the AppDomain in question.

大多数示例如何在PowerShell中覆盖默认验证的说明将告诉您要做:

Most examples of how to override the default validation in PowerShell will tell you to just do:

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

不要这样做!完全绕过验证。

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

What you can do, is implement a proper callback function and invoke chain validation manually. Before you do this, you can add certificates not in the machine or user certificate store to the list of chains you can validate against:

$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证书,对不起

I don't know how to read multiple certificates from a PEM file into a certificate collection, so you'll have to add each ca cert one by one, sorry

这篇关于如何使用cacert文件在Powershell(Invoke-WebRequest)中执行等效的cUrl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆