gpt4 book ai didi

PowerShell错误: The Underlying connection was closed

转载 作者:行者123 更新时间:2023-12-03 08:59:00 33 4
gpt4 key购买 nike

我正在尝试使用 Invoke-WebRequest cmdlet(第一次)连接到 Sharp 打印机的 Web 界面。到目前为止,我的代码如下:

$cred = Get-Credential
$url = 'http://<IP address of printer>/login.html?/main.html'
$login = Invoke-WebRequest $url -SessionVariable printer -Method Get
$login.Forms[0].Fields.element10002 = $cred.UserName
$login.Forms[0].Fields.element10002 =
$cred.GetNetworkCredential().Password
$mainPage = Invoke-WebRequest -Uri ($url + $login.Forms[0].Action) `
-WebSession $printer -Body $login -Method Post

...但我不断收到此错误:

Invoke-WebRequest : The underlying connection was closed: The connection
was closed unexpectedly.
At line:6 char:13
+ $mainPage = Invoke-WebRequest -Uri ($url + $login.Forms[0].Action) -W
...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation:
(System.Net.HttpWebRequest
:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId :
WebCmdletWebResponseException,Microsoft.Powe
rShell.Commands.InvokeWebRequestCommand

这行代码不会导致错误:

$login = Invoke-WebRequest $url -SessionVariable printer -Method Get

但是这一行确实:

$mainPage = Invoke-WebRequest -Uri ($url + $login.Forms[0].Action) ` 
-WebSession $printer -Body $login -Method Post

我在 Windows 7 机器上使用 PS 版本 5.1 和 Tls12。经过一番谷歌搜索后,这个问题似乎与 Tls 的版本有关。但我不知道将其更改为什么。

有人有什么想法吗? - @leah_cyberpadawan

最佳答案

在使用可能具有自签名证书或仅支持 TLS 1.2 的端点时,以下两个解决方案对我有用:

[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
Add-Type -TypeDefinition @'
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy
{
public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int certProblem)
{
return true;
}
}
'@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object -TypeName TrustAllCertsPolicy

[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

关于PowerShell错误: The Underlying connection was closed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52501377/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com