PowerShell的V3调用-的WebRequest HTTPS错误(Powershell v3

2019-06-17 13:34发布

使用PowerShell v3的的Invoke-WebRequest类和调用,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}

有人可以提供什么可能是错误怎么回事,以及如何解决它的一些guideance?

谢谢

Answer 1:

这种变通为我工作: 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"


Answer 2:

李的回答是伟大的,但我也有与协议所支持的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


Answer 3:

你有没有尝试使用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)


Answer 4:

我发现,当我用这个回调函数忽略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 } 



Answer 5:

我下面的奋力工作(并采用了最新的非过时的手段与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/



Answer 6:

我试图寻找在EM7开源REST API文档。 至今没有运气。

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

有很多谈论开源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

卷曲式的header

$b.Headers

我测试的IRM / IWR与Twitter的JSON API。

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

希望这可以帮助。



Answer 7:

  1. 运行此命令

新SelfSignedCertificate -certstorelocation证书:\ LOCALMACHINE \我-dnsname {您的站点主机名}

使用管理员权限 PowerShell中,这将在个人目录中的所有证书

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

确保网站的主机名和证书DNS名称应该完全匹配



Answer 8:

如果运行此作为管理员,这个错误应该消失



Answer 9:

这些注册表设置影响的.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



Answer 10:

在纯替代实现的powershell (无Add-Type的C#源):

#requires -Version 5

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()


文章来源: Powershell v3 Invoke-WebRequest HTTPS error