Powershell v3 Invoke-WebRequest HTTPS 错误

使用 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 cert,但是我不确定它是否实际上在做任何事情。

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

有人能提供一些指导,什么可能是错误的,以及如何修复它?

谢谢

321577 次浏览

你试过用 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)

我试着搜索关于 EM7 OpenSource REST API 的文档,到目前为止还没有找到。

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

有很多关于 OpenSourceRESTAPI 的讨论,但是没有链接到实际的 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

希望这个能帮上忙。

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

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

我找到了这个 论坛帖子,它将我引向下面的函数。我在另一个代码的作用域内运行一次,它就可以工作了。

函数 Ignore-SSL 证书
{
$Provider = New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler = $Provider. CreateCompiler ()
$Params = New-Object System. CodeDom. Compiler. CompilerParameter
$Params. GenerateExecute = $false
$Params. GenerateInMemory = $true
$Params. IncludeDebugInformation = $false
$Params. ReferencedAssembly. Add (“ System.DLL”) > $null
$TASsource =@’
名称空间 Local.ToolkitExtensions.Net
{
公共类 TrustAll: System.Net.ICertificatePolicy
{
Public bool CheckValidationResult (System. Net. ServicePoint sp,System. Security. Cryptography.X509證 icates.X509Securities cert,System. Net. WebRequest req,int problem)
{
返回真;
}
}
}
'@
$TAResults = $Provider. CompileAssemblyFromSource ($Params,$TASsource)
$TAAssembly = $TAResults. CompiledAssembly
# # 我们创建一个 TrustAll 的实例并将其附加到 ServicePointManager
$TrustAll = $TAAssembly. CreateInstance (“ Local. ToolkitExtensions.Net. CericatePolicy. TrustAll”)
[ System.Net.ServicePointManager ] : : 证书策略 = $TrustAll
}

这个解决办法对我很有效: 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"

下面的方法对我很有效(并且使用最新的非推荐方法与 SSL Certs/callback 功能进行交互) ,而且不会尝试在相同的 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/

  1. 运行这个命令

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

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

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

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

Lee 的回答很好,但是我也对 Web 服务器支持的协议有疑问。
After also adding the following lines, I could get the https request through. As pointed out in this answer https://stackoverflow.com/a/36266735

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

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

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

这些注册表设置影响。NETFramework4 + ,因此是 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://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls#schusestrongcrypto

在纯 中的替代实现(没有 源的 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()

Invoke-WebRequest“ DomainName”-Skip證 icateCheck

可以使用 - 跳过证书检查参数作为一行命令来实现此目的(此参数仅在核心 PSEDITION 上支持)