Bootstrap FreeKB - PowerShell - Connect to an FTP Server
PowerShell - Connect to an FTP Server

Updated:   |  PowerShell articles

Here is how you can test connection to an FTP server using PowerShell.

$server = "server1.example.com"
$port = "21"

try {
  $client = New-Object System.Net.Sockets.TcpClient("$server", $port)
  $client.Close()
  Write-Output "Successfully Connected to $server on port $port"
}
catch {
  Write-Output "Connection Failed: $($_.Exception.Message)"
}
exit

 

If the connection fails, something like this should be returned.

Connection Failed: Exception calling ".ctor" with "2" argument(s): "No such host is known"

 

On the other hand, if the connection is successful, something like this should be returned.

Successfully Connected to server1.example.com on port 21

 

Then you could include the following to test logging into the FTP server.

$username = "john.doe"
$password = "itsasecret" 

try {
  $ftp = [System.Net.FtpWebRequest]::create("ftp://$server/")
  $ftp.Credentials =  New-Object System.Net.NetworkCredential($username,$password)
  $ftp.Method = [System.Net.WebRequestMethods+Ftp]::PrintWorkingDirectory
  $ftp.GetResponse()
  Write-Output "Successfully logged into $server on port $port as $username"
}
catch {
  Write-Output "Failed to log into $server on port $port as $username"
  Write-Output "$($_.Exception.Message)"
  exit
}

 

If the log in is successful, something like this should be returned.

ContentLength           : 0
Headers                 : {}
SupportsHeaders         : True
ResponseUri             : ftp://server1.example.com/
StatusCode              : PathnameCreated
StatusDescription       : 257 "/" is your current location
                          
LastModified            : 1/1/0001 12:00:00 AM
BannerMessage           : 220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
                          220-You are user number 1 of 50 allowed.
                          220-Local time is now 00:12. Server port: 21.
                          220-IPv6 connections are also welcome on this server.
                          220 You will be disconnected after 15 minutes of inactivity.
                          
WelcomeMessage          : 230 OK. Current restricted directory is /
                          
ExitMessage             : 
IsFromCache             : False
IsMutuallyAuthenticated : False
ContentType             : 

Successfully logged into lab1.software.eng.us on port 21 as john.doe

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 414d68 in the box below so that we can be sure you are a human.