>最近我在连接到FTP服务器时遇到了一些问题,但是会有一些弹出窗口要求接受证书。
我不知道如何在调用方法$ftpRequest.GetResponse()
期间通过PowerShell克服此问题。我找到了一些关于覆盖证书上的回调方法的解决方案,例如[System.Net.ServicePointManager]::ServerCertificateValidationCallback
解决方案是在C#上给出的,我还不知道如何将其移植到PowerShell。
我的代码如下
function Create-FtpDirectory {
param(
[Parameter(Mandatory=$true)]
[string]
$sourceuri,
[Parameter(Mandatory=$true)]
[string]
$username,
[Parameter(Mandatory=$true)]
[string]
$password
)
if ($sourceUri -match '\$|\w+$') { throw 'sourceuri should end with a file name' }
$ftprequest = [System.Net.FtpWebRequest]::Create($sourceuri);
Write-Information -MessageData "Create folder to store backup (Get-FolderName -Path $global:backupFolder)"
$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::MakeDirectory
$ftprequest.UseBinary = $true
$ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password)
$ftprequest.EnableSsl = $true
$response = $ftprequest.GetResponse();
Write-Host "Folder created successfully, status $response.StatusDescription"
$response.Close();
}
[更新] 在搜索Invoke-RestRequest时,我从Microsoft示例中找到了这个解决方案
注意:这实际上是接受任何证书
# Next, allow the use of self-signed SSL certificates.
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $True }
更多信息(感谢@Nimral(:https://learn.microsoft.com/en-us/dotnet/api/system.net.servicepointmanager.servercertificatevalidationcallback?view=netcore-3.1
这有点麻烦,但您可以通过Add-Type
在 PowerShell 中使用原始 C#。下面是一个示例类,我用来在当前 PowerShell 会话中切换证书验证。
if (-not ([System.Management.Automation.PSTypeName]'CertValidation').Type)
{
Add-Type @"
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public class CertValidation
{
static bool IgnoreValidation(object o, X509Certificate c, X509Chain ch, SslPolicyErrors e) {
return true;
}
public static void Ignore() {
ServicePointManager.ServerCertificateValidationCallback = IgnoreValidation;
}
public static void Restore() {
ServicePointManager.ServerCertificateValidationCallback = null;
}
}
"@
}
然后,您可以在像这样调用函数之前使用它。
[CertValidation]::Ignore()
稍后,像这样还原默认证书验证。
[CertValidation]::Restore()
但请记住,仅修复服务的证书要安全得多,以便验证实际成功。如果您无法控制环境,则忽略证书验证应该是您的最后手段。