使用 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}
有人可以就这里可能出现的问题以及如何解决它提供一些指导吗?
谢谢
Invoke-RestMethod
还是 Invoke-WebRequest
?
Invoke-WebRequest : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
您可以尝试探索 $Error[0].Exception.InnerException 以获得更多信息信息...
基本上,在您的 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"
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
SecurityProtocol
全局静态属性。天哪,我刚刚在检查证书、信任、网络、路由、权限和其他东西上浪费了几天时间,试图解决通过 https 访问一个特定服务器时出现的模糊 endpoint does not respond
错误(所有其他都可以工作),只是因为那个该死的 powershell 5.1 默认为 SSL3,TLS,它只是 BLOCKS GODDAMN TLS11 和 TLS12 BY DEFAULT 天哪,我多么讨厌这个废话,我应该用 C#/Ruby/ 编写那个脚本C ++,或其他任何不是powershell的东西
纯 powershell 中的替代实现(没有 c# 源的 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()
您是否尝试使用 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)
以下工作对我有用(并使用最新的非弃用方式与 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/
调用-WebRequest“域名”-SkipCertificateCheck
您可以使用 -SkipCertificateCheck 参数将其作为单行命令来实现(此参数仅支持核心 PSEDITION)
我发现当我使用这个回调函数忽略 SSL 证书 [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
我总是收到错误消息 Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
,这听起来像是您的结果。
我找到了这个 forum post,它引导我使用下面的函数。我在其他代码的范围内运行了一次,它对我有用。
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
}
我尝试搜索有关 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
希望这可以帮助。
这些注册表设置会影响 .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
运行此命令
New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname {your-site-hostname}
在 powershell 中使用管理员权限,这将在 Personal 目录中生成所有证书
要摆脱隐私错误,请选择这些证书,右键单击 → 复制。并粘贴在受信任的根证书颁发机构/证书中。最后一步是在 IIS 中选择正确的绑定。转到 IIS 网站,选择 Bindings,选择 SNI 复选框并为每个网站设置单独的证书。
确保网站主机名和证书 dns-name 应该完全匹配
如果您以管理员身份运行它,该错误应该会消失
-SkipCertificateCheck
。