138

使用 Powershell v3 的 Invoke-WebRequest 和 Invoke-RestMethod 我已成功使用 POST 方法将 json 文件发布到 https 网站。

我正在使用的命令是

 $cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("cert.crt")
 Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert -Body $json -ContentType application/json -Method POST

但是,当我尝试使用 GET 方法时:

 Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert -Method GET

返回以下错误

 Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
 At line:8 char:11
 + $output = Invoke-RestMethod -Uri https://IPADDRESS/resource -Credential $cred
 +           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest)      [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

我尝试使用以下代码忽略 SSL 证书,但我不确定它是否真的在做任何事情。

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

有人可以就这里可能出现的问题以及如何解决它提供一些指导吗?

谢谢

4

11 回答 11

203

这种解决方法对我有用: http ://connect.microsoft.com/PowerShell/feedback/details/419466/new-webserviceproxy-needs-force-parameter-to-ignore-ssl-errors

基本上,在您的 PowerShell 脚本中:

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

$result = Invoke-WebRequest -Uri "https://IpAddress/resource"
于 2013-04-05T19:20:05.170 回答
85

Lee 的回答很好,但我也遇到了 Web 服务器支持的协议的问题。
在还添加以下行之后,我可以通过 https 请求。正如这个答案中指出的那样https://stackoverflow.com/a/36266735

$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols

我对李的代码的完整解决方案。

add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
    public bool CheckValidationResult(
        ServicePoint srvPoint, X509Certificate certificate,
        WebRequest request, int certificateProblem) {
        return true;
    }
}
"@
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
于 2017-09-16T13:43:25.643 回答
15

Add-Type中的替代实现(没有源代码):

#requires -Version 5
#requires -PSEdition Desktop

class TrustAllCertsPolicy : System.Net.ICertificatePolicy {
    [bool] CheckValidationResult([System.Net.ServicePoint] $a,
                                 [System.Security.Cryptography.X509Certificates.X509Certificate] $b,
                                 [System.Net.WebRequest] $c,
                                 [int] $d) {
        return $true
    }
}
[System.Net.ServicePointManager]::CertificatePolicy = [TrustAllCertsPolicy]::new()
于 2019-03-19T16:59:51.937 回答
10

你试过用System.Net.WebClient吗?

$url = 'https://IPADDRESS/resource'
$wc = New-Object System.Net.WebClient
$wc.Credentials = New-Object System.Net.NetworkCredential("username","password")
$wc.DownloadString($url)
于 2012-07-31T12:51:12.947 回答
8

调用-WebRequest“域名”-SkipCertificateCheck

您可以使用-SkipCertificateCheck参数将其作为单行命令来实现(此参数仅支持核心 PSEDITION)

于 2020-05-19T08:56:05.063 回答
7

以下工作对我有用(并使用最新的非弃用方式与 SSL 证书/回调功能进行交互),并且不会尝试在同一个 powershell 会话中多次加载相同的代码:

if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
{
$certCallback=@"
    using System;
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    public class ServerCertificateValidationCallback
    {
        public static void Ignore()
        {
            if(ServicePointManager.ServerCertificateValidationCallback ==null)
            {
                ServicePointManager.ServerCertificateValidationCallback += 
                    delegate
                    (
                        Object obj, 
                        X509Certificate certificate, 
                        X509Chain chain, 
                        SslPolicyErrors errors
                    )
                    {
                        return true;
                    };
            }
        }
    }
"@
    Add-Type $certCallback
 }
[ServerCertificateValidationCallback]::Ignore();

这改编自以下文章 https://d-fens.ch/2013/12/20/nobrainer-ssl-connection-error-when-using-powershell/

于 2016-08-02T19:33:29.487 回答
5

我发现当我使用这个回调函数忽略 SSL 证书时[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

我总是收到错误消息Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.,这听起来像是您得到的结果。

我找到了这个论坛帖子,它引导我使用下面的功能。我在其他代码的范围内运行了一次,它对我有用。

function Ignore-SSLCertificates
{
    $Provider = New-Object Microsoft.CSharp.CSharpCodeProvider
    $Compiler = $Provider.CreateCompiler()
    $Params = New-Object System.CodeDom.Compiler.CompilerParameters
    $Params.GenerateExecutable = $false
    $Params.GenerateInMemory = $true
    $Params.IncludeDebugInformation = $false
    $Params.ReferencedAssemblies.Add("System.DLL") > $null
    $TASource=@'
        namespace Local.ToolkitExtensions.Net.CertificatePolicy
        {
            public class TrustAll : System.Net.ICertificatePolicy
            {
                public bool CheckValidationResult(System.Net.ServicePoint sp,System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Net.WebRequest req, int problem)
                {
                    return true;
                }
            }
        }
'@ 
    $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
    $TAAssembly=$TAResults.CompiledAssembly
    ## We create an instance of TrustAll and attach it to the ServicePointManager
    $TrustAll = $TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
    [System.Net.ServicePointManager]::CertificatePolicy = $TrustAll
}

于 2013-03-26T00:50:20.900 回答
1

我尝试搜索有关 EM7 OpenSource REST API 的文档。到目前为止没有运气。

http://blog.sciencelogic.com/sciencelogic-em7-the-next-generation/05/2011

有很多关于 OpenSource REST API 的讨论,但没有指向实际 API 或任何文档的链接。也许是我不耐烦了。

您可以尝试以下几件事

$a = Invoke-RestMethod -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert 
$a.Results | ConvertFrom-Json

试试这个看看你是否可以过滤掉你从 API 获得的列

$a.Results | ft

或者,您也可以尝试使用它

$b = Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert 
$b.Content | ConvertFrom-Json

卷曲样式标题

$b.Headers

我使用 twitter JSON api 测试了 IRM / IWR。

$a = Invoke-RestMethod http://search.twitter.com/search.json?q=PowerShell 

希望这可以帮助。

于 2012-08-01T03:21:16.520 回答
0

这些注册表设置会影响 .NET Framework 4+,因此也会影响 PowerShell。设置它们并重新启动任何 PowerShell 会话以使用最新的 TLS,无需重新启动。

Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord 

请参阅https://docs.microsoft.com/en-us/dotnet/framework/network-programming/tls#schusestrongcrypto

于 2018-09-05T22:10:56.220 回答
-1
  1. 运行此命令

New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname {your-site-hostname}

在 powershell 中使用管理员权限,这将在 Personal 目录中生成所有证书

  1. 要摆脱隐私错误,请选择这些证书,右键单击 → 复制。并粘贴在受信任的根证书颁发机构/证书中。
  2. 最后一步是在 IIS 中选择正确的绑定。转到 IIS 网站,选择 Bindings,选择 SNI 复选框并为每个网站设置单独的证书。

确保网站主机名和证书 dns-name 应该完全匹配

于 2017-05-26T14:37:24.693 回答
-1

如果您以管理员身份运行它,该错误应该会消失

于 2017-06-21T17:08:37.173 回答