【问题标题】:Using PowerShell to test an FTP connection使用 PowerShell 测试 FTP 连接
【发布时间】:2018-06-18 08:44:32
【问题描述】:

我有一个在某些服务器上执行检查的 PowerShell 脚本,例如 Test-Connection 用于 PING。

我希望通过执行“FTP Open”命令来检查其中一台具有 FTP 服务器的服务器。我不需要登录或上传/下载任何文件,只需要知道 FTP 服务器是否响应。

我在互联网上的大部分研究都指向设置凭据和导入专有模块以进行连接,可能是上传或下载文件,但我只需要一个简单的方法来打开连接并告诉我是否存在响应服务器。

我运行这个脚本的服务器应该安装了最少的软件,但如果它需要任何东西,最好是微软和他们的网站。

【问题讨论】:

    标签: powershell ftp


    【解决方案1】:

    Test-NetConnection 是原生 Powershell,可用于测试 FTP 端口 21 上的简单连接:

    Test-NetConnection -ComputerName ftp.contoso.com -Port 21
    

    【讨论】:

    • 优秀。不需要启用 telnet。
    【解决方案2】:

    没有什么像 FTP 命令“打开”。

    但也许您的意思只是测试服务器是否侦听 FTP 端口 21:

    try
    {
        $client = New-Object System.Net.Sockets.TcpClient("ftp.example.com", 21)
        $client.Close()
        Write-Host "Connectivity OK."
    }
    catch
    {
        Write-Host "Connection failed: $($_.Exception.Message)"
    }
    

    如果您想在不实际登录的情况下测试 FTP 服务器是否正常运行,请使用带有错误凭据的FtpWebRequest,并检查您是否收到了适当的错误消息。

    try
    {
        $ftprequest = [System.Net.FtpWebRequest]::Create("ftp://ftp.example.com")
        $ftprequest.Credentials = New-Object System.Net.NetworkCredential("wrong", "wrong") 
        $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::PrintWorkingDirectory
        $ftprequest.GetResponse()
    
        Write-Host "Unexpected success, but OK."
    }
    catch
    {
        if (($_.Exception.InnerException -ne $Null) -and
            ($_.Exception.InnerException.Response -ne $Null) -and
            ($_.Exception.InnerException.Response.StatusCode -eq
                 [System.Net.FtpStatusCode]::NotLoggedIn))
        {
            Write-Host "Connectivity OK."
        }
        else
        {
            Write-Host "Unexpected error: $($_.Exception.Message)"
        }
    }
    

    【讨论】:

    • 我喜欢第一个解决方案 - 我打算建议这样做(类似于测试连接),但不确定如何实现。
    猜你喜欢
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2017-05-02
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多