Pages

Saturday, January 31, 2015

Connect to a SFTP site using Windows Powershell

This post explains how to access  a SFTP server using Windows Powershell commands. There are many file transfer utilities which can be used for this purpose. Here, I use WinSCP  in order to access SFTP server from windows powershell.

1. WinSCP PowerShell Wrapper can be downloaded from https://github.com/dotps1/WinSCP.
2. Import WinSCP Powershell module. $WinSCPFile path variable needs to be set to the WinSCP.psd1 file inside the downloaded folder.

$WinSCPFile = "C:\....\WinSCP-master\WinSCP.psd1"
Import-Module -Name $WinSCPFile -Verbose -ErrorAction Inquire -WarningAction Inquire | Out-null
3. Splat New-WinSCPSessionOptions.
$sessionOptions = @{
HostName = "SFTP-HostName"
UserName = "Username"
Password = "Password"
SshHostKeyFingerprint = "HostKey"
}


To get the SshHostKeyFingerprint, go to \WinSCP-master\NeededAssemblies\ folder and run WinSCP.exe.Then enter HostName, Username, & Password and try connecting to the SFTP site. You will get the SshHostKeyFingerprint when you log in for the first time.

4. Open new WinSCPSession using the splatted parameters.
$session = Open-WinSCPSession -SessionOptions (New-WinSCPSessionOptions @sessionOptions)
 

5. Send a file to SFTP server
Send-WinSCPItem -WinSCPSession $session -LocalPath "C:\localFile.txt" -RemotePath "./remoteDirectory/"
 

6. Get a file from FTP server
Receive-WinSCPItem -WinSCPSession $session -RemotePath "./remoteDirectory/rFile.txt" -LocalPath "C:\localFile.txt"
7. Close SFTP session
Close-WinSCPSession -WinSCPSession $session

Referance: 

https://github.com/dotps1/WinSCP
http://winscp.net/eng/docs/ssh_verifying_the_host_key

1 comment:

  1. You can actually use the Get-WinSCPSshHostKeyFingerprint cmdlet I implemented to get the value, rather then running the exe. https://github.com/dotps1/WinSCP/wiki/Get-WinSCPSshHostKeyFingerprint#example-1

    ReplyDelete