Post a reply

Options
Add an Attachment

If you do not want to add an Attachment to your Post, please leave the Fields blank.

(maximum 10 MB; please compress large files; only common media, archive, text and programming file formats are allowed)

Options

Topic review

sirjig

Connect SFTP using fingerprint and passphrase

Hello guys, I need to write a code using PowerShell to connect to SFTP using private key. When I use the GUI, always ask for the passphrase, and that's ok for me, but when try to make a code for this and do not ask for the passphrase, it becomes a madness, please, help me, thanks.

Gus.
Part of the code in PS
# Load WinSCP .NET assembly
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
# Set up session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Sftp
    HostName = "xxxx.xxxx.xxxx"
    UserName = "xxxxxx"
    Password = "xxxxxx"
    SshHostKeyFingerprint = "ssh-rsa 2048 df769da876gsf798g7gd"
    SshPrivateKeyPath = "D:\Bops-SFTP\clave_privada.ppk"
}
 
$session = New-Object WinSCP.Session
 
try
{
    # Connect
    $session.Open($sessionOptions)
 
    # Your code
}
finally
{
    $session.Dispose()
}

When make the connection I get this error
Exception calling "Open" with "1" argument(s): "Connection has been unexpectedly closed. Server sent command exit status 0.

Authentication log (see session log for details):
Using username "xxxxxx".
Authenticating with public key "xxxxxxx".
Authentication failed."
At line:18 char:5
+     $session.Open($sessionOptions)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SessionRemoteException
credman

CredentialManager module

Use the CredentialManager module with the password added in Control Panel - Credential Manager.
s31064

PowerShell Script Password Encryption

I'm posting this because it took me two days to figure out. I needed a script I could run in a room full of backseat drivers. I couldn't hardcode the username and password into the script, and I didn't want to use Read-Host with people looking over my shoulder. This is what I came up with:
$Creds = Get-Credential
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Sftp
    HostName = "sftp.url.com"
    UserName = $Creds.UserName
    Password = (ConvertFrom-SecureToPlain -SecurePassword $Creds.Password)
    SshHostKeyFingerprint = "redacted gobbledegook"
}

Works like a charm. I get a username/password popup from Get-Credential where the password shows as *****, and the (ConvertFrom-SecureToPlain -SecurePassword $Creds.Password) converts the password into something the SFTP server understands.

Hope this helps someone.