通过PowerShell在FtpWebRequest期间永久接受证书

时间:2018-05-16 04:09:49

标签: powershell x509certificate powershell-v4.0

最近我遇到了一些与FTP服务器连接的问题,但会有一些弹出窗口要求验证证书。

我不知道如何在调用方法$ftpRequest.GetResponse()期间通过PowerShell克服这个问题。我找到了一些关于覆盖证书上的回调方法的解决方案,例如[System.Net.ServicePointManager]::ServerCertificateValidationCallback

解决方案是在C#& amp;我还不知道如何将它移植到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();
}

2 个答案:

答案 0 :(得分:0)

有点hacky,但您可以通过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()

请记住,虽然修复服务证书更安全,但验证确实成功。如果您无法控制环境,则忽略证书验证应该是最后的手段。

答案 1 :(得分:0)

在搜索Invoke-RestRequest时,我从Microsoft示例

中找到了此解决方案
# Next, allow the use of self-signed SSL certificates.

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $True }

https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Invoke-RestMethod?view=powershell-4.0

相关问题