5
votes

I have a PowerShell script that performs checks on some servers, for example Test-Connection for PING.

I wish to check one of the servers that has an FTP server by performing an "FTP Open" command. I don't need to log in or upload/download any files, just need to know if the FTP server responds or not.

Most of my research on the internet points to setting up credentials and importing proprietary modules to connect, perhaps uploading or downloading files, but I just need a simple method to open the connection and tell me either true or false if there is a responding server.

The server I am running this script from should have minimal software installed, but if it needs anything, preferably Microsoft and from their website.

2

2 Answers

9
votes

Test-NetConnection is native Powershell and can be used to test simple connectivity on FTP Port 21:

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

There's nothing like FTP command "open".

But maybe you mean to just test that the server listens on FTP port 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)"
}

If you want to test that the FTP server is behaving, without actually logging in, use FtpWebRequest with wrong credentials and check that you get back an appropriate error message.

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)"
    }
}