5

执行Invoke-WebRequest -Uri https://www.freehaven.net/anonbib/date.htmlPowerShell 行时会抛出WebCmdletResponseException. 我怎样才能获得有关它的更多信息,以及可能导致这种情况的原因是什么?虽然我可以使用 Python 成功获取页面的内容,但在 PowerShell 中它会引发异常。

完全例外:

Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
At line:1 char:1
+ Invoke-WebRequest -Uri https://www.freehaven.net/anonbib/date.html
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc
   eption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
4

1 回答 1

8

这是因为在后台Invoke-WebRequest使用HttpWebRequest,除了最新版本的 .Net 之外,其他所有版本都默认使用 SSLv3 和 TLSv1。

您可以通过查看当前值来看到这一点:

[System.Net.ServicePointManager]::SecurityProtocol

您要连接的站点仅支持 TLS 1.2 。

您可以更改允许的协议,但它会在应用程序运行期间全局应用:

[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12

这会覆盖该值。

当然,这会破坏您的应用程序中依赖与不支持 TLS 1.2 的服务器的连接的任何其他内容

一种安全的方法可能是添加TLS 1.2:

[System.Net.ServicePointManager]::SecurityProtocol] = (
    [System.Net.ServicePointManager]::SecurityProtocol -bor 
    [System.Net.SecurityProtocolType]::Tls12
)

# parentheses are for readability

万一这仍然会给其他站点带来问题(不确定是什么,也许一个站点说它接受 TLS 1.2 但它的实现被破坏了,而它的 TLS 1.0 工作正常?),您可以保存以前的值并恢复它.

$cur = [System.Net.ServicePointManager]::SecurityProtocol]
try {
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
    Invoke-WebRequest -Uri https://www.freehaven.net/anonbib/date.html
} finally {
    [System.Net.ServicePointManager]::SecurityProtocol = $cur
}
于 2018-02-04T00:14:00.560 回答