.net Powershell v3 Invoke-WebRequest HTTPS 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11696944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Powershell v3 Invoke-WebRequest HTTPS error
提问by floyd
Using Powershell v3's Invoke-WebRequest and Invoke-RestMethod I have succesfully used the POST method to post a json file to a https website.
使用 Powershell v3 的 Invoke-WebRequest 和 Invoke-RestMethod 我已经成功地使用 POST 方法将 json 文件发布到 https 网站。
The command I'm using is
我正在使用的命令是
$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
However when I attempt to use the GET method like:
但是,当我尝试使用 GET 方法时:
Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert -Method GET
The following error is returned
返回以下错误
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
I have attempted using the following code to ignore SSL cert, but I'm not sure if its actually doing anything.
我尝试使用以下代码忽略 SSL 证书,但我不确定它是否真的在做任何事情。
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
Can someone provide some guideance on what might be going wrong here and how to fix it?
有人可以就此处可能出现的问题以及如何解决问题提供一些指导吗?
Thanks
谢谢
回答by Lee Grissom
This work-around worked for me: http://connect.microsoft.com/PowerShell/feedback/details/419466/new-webserviceproxy-needs-force-parameter-to-ignore-ssl-errors
这个解决方法对我有用:http: //connect.microsoft.com/PowerShell/feedback/details/419466/new-webserviceproxy-needs-force-parameter-to-ignore-ssl-errors
Basically, in your PowerShell script:
基本上,在您的 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"
回答by AndOs
Lee's answer is great, but I also had issues with which protocols the web server supported.
After also adding the following lines, I could get the https request through. As pointed out in this answer https://stackoverflow.com/a/36266735
Lee 的回答很好,但我也遇到了 Web 服务器支持哪些协议的问题。
在添加以下几行之后,我可以通过 https 请求。正如这个答案中所指出的https://stackoverflow.com/a/36266735
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
My full solution with Lee's code.
我使用 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
回答by Sunny Chakraborty
Did you try using System.Net.WebClient?
你试过用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)
回答by Maximilian Burszley
An alternative implementation in pure powershell(without Add-Typeof c#source):
在纯替代实现的powershell(没有Add-Type的C#源):
#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()
回答by Arthur Strutzenberg
The following worked worked for me (and uses the latest non deprecated means to interact with the SSL Certs/callback functionality), and doesn't attempt to load the same code multiple times within the same powershell session:
以下对我有用(并使用最新的非弃用方法与 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();
This was adapted from the following article https://d-fens.ch/2013/12/20/nobrainer-ssl-connection-error-when-using-powershell/
这是改编自以下文章 https://d-fens.ch/2013/12/20/nobrainer-ssl-connection-error-when-using-powershell/
回答by Aaron D
I found that when I used the this callback function to ignore SSL certificates [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
我发现当我使用这个回调函数来忽略 SSL 证书时 [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
I always got the error message Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.which sounds like the results you are having.
我总是收到错误消息Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.,听起来像您所拥有的结果。
I found this forum postwhich lead me to the function below. I run this once inside the scope of my other code and it works for me.
我找到了这个论坛帖子,它引导我进入下面的功能。我在其他代码的范围内运行了一次,它对我有用。
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
}回答by Autonomic
If you run this as administrator, that error should go away
如果您以管理员身份运行此程序,该错误应该会消失
回答by Sunny Chakraborty
I tried searching for documentation on the EM7 OpenSource REST API. No luck so far.
我尝试搜索有关 EM7 OpenSource REST API 的文档。到目前为止没有运气。
http://blog.sciencelogic.com/sciencelogic-em7-the-next-generation/05/2011
http://blog.sciencelogic.com/sciencelogic-em7-the-next-generation/05/2011
There's a lot of talk about OpenSource REST API, but no link to the actual API or any documentation. Maybe I was impatient.
有很多关于 OpenSource REST API 的讨论,但没有指向实际 API 或任何文档的链接。也许是我不耐烦了。
Here are few things you can try out
您可以尝试以下几件事
$a = Invoke-RestMethod -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert
$a.Results | ConvertFrom-Json
Try this to see if you can filter out the columns that you are getting from the API
试试这个,看看你是否可以过滤掉你从 API 获取的列
$a.Results | ft
or, you can try using this also
或者,您也可以尝试使用它
$b = Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert
$b.Content | ConvertFrom-Json
Curl Style Headers
卷曲样式标题
$b.Headers
I tested the IRM / IWR with the twitter JSON api.
我使用 twitter JSON api 测试了 IRM/IWR。
$a = Invoke-RestMethod http://search.twitter.com/search.json?q=PowerShell
Hope this helps.
希望这可以帮助。
回答by Mohit Dharmadhikari
- Run this command
- 运行这个命令
New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname {your-site-hostname}
New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname {your-site-hostname}
in powershell using admin rights, This will generate all certificates in Personal directory
在 powershell 中使用管理员权限,这将在 Personal 目录中生成所有证书
- To get rid of Privacy error, select these certificates, right click → Copy. And paste in Trusted Root Certification Authority/Certificates.
- Last step is to select correct bindings in IIS. Go to IIS website, select Bindings, Select SNI checkbox and set the individual certificates for each website.
- 要摆脱隐私错误,请选择这些证书,右键单击 → 复制。并粘贴受信任的根证书颁发机构/证书。
- 最后一步是在 IIS 中选择正确的绑定。转到 IIS 网站,选择绑定,选择 SNI 复选框并为每个网站设置单独的证书。
Make sure website hostname and certificate dns-name should exactly match
确保网站主机名和证书 dns-name 应该完全匹配
回答by Jeremy Cook
These registry settings affect .NET Framework 4+ and therefore PowerShell. Set them and restart any PowerShell sessions to use latest TLS, no reboot needed.
这些注册表设置影响 .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
See https://docs.microsoft.com/en-us/dotnet/framework/network-programming/tls#schusestrongcrypto
请参阅https://docs.microsoft.com/en-us/dotnet/framework/network-programming/tls#schusestrongcrypto

