0 votes
by (120 points)

Are there any examples, using PowerShell (or perhaps something I can interpret - not a programmer... :( ) that I can use for SSH Private key authentication + passphrase to an SFTP server?

Thanks in advance!

1 Answer

0 votes
by (147k points)

There are two samples on our blog, and I'm adding additional samples here.

This connects to our demo server, lists the root directory contents and downloads the readme.txt file:

# load Rebex SFTP assemblies
Add-Type -Path "c:\Program Files (x86)\Rebex Components 2017 R4.1\bin\net-4.0\Rebex.Common.dll" 
Add-Type -Path "c:\Program Files (x86)\Rebex Components 2017 R4.1\bin\net-4.0\Rebex.Networking.dll" 
Add-Type -Path "c:\Program Files (x86)\Rebex Components 2017 R4.1\bin\net-4.0\Rebex.Sftp.dll" 

# create an instance of Sftp object
$sftp = New-Object Rebex.Net.Sftp

# omit this if logging is not needed (or use FileLogWriter to log into a file)
$sftp.LogWriter = New-Object Rebex.ConsoleLogWriter([Rebex.LogLevel]::Info)

# connect and authenticate
$sftp.Connect("test.rebex.net")
$sftp.Login("demo", "password") 

# display contents of the root directory (use GetList to get a parsed form)
Write-Output $sftp.GetRawList("/")

# download a file into the current directory
$sftp.Download("/readme.txt", ".")

# disconnect from the server and dispose the sftp object
$sftp.Disconnect()
$sftp.Dispose()

To authenticate using a private key instead of a password, use create an instance of SshPrivateKey and use another overload of the Login method:

...
$key = New-Object Rebex.Net.SshPrivateKey("C:\MyData\Key.ppk", "keypassword")
$sftp.Login("username", $key) 
...

And to use both a key and password, use this:

...
$key = New-Object Rebex.Net.SshPrivateKey("C:\MyData\Key.ppk", "keypassword")
$sftp.Login("username", "password", $key) 
...

Most methods of the Sftp object are simple-to-use and quite suitable to be called from PowerShell scripts - converting the sample code from our features pages should be quite simple.

...