Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PowerShell to test an FTP connection

Tags:

powershell

ftp

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.

like image 606
TOGEEK Avatar asked Jan 09 '18 10:01

TOGEEK


People also ask

Can you use PowerShell for FTP?

You are able to upload files to the FTP server using Powershell.

Can you ping from PowerShell?

So, how do you ping in PowerShell? Use the 'Test-Connection' applet. It's that easy. Much like you would use 'ping' in CMD, type in 'Test-Connection' followed by '-Ping', '-TargetName', and an IP address to send a ping to that device.


2 Answers

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
like image 131
henrycarteruk Avatar answered Oct 19 '22 10:10

henrycarteruk


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)"
    }
}
like image 35
Martin Prikryl Avatar answered Oct 19 '22 10:10

Martin Prikryl