I have a C# .NET project, where am trying to open an SFTP connection to a server and put a file to the server.
I have SFTP hostname, username and key file (.pem file).
I do not have a password here.
Please help me with something to use SFTP in C# and .Net.
Right-click the icon and select “Add Key” and select your private key (PPK) file. Follow the prompt to enter your pass phrase and you're done. Now simply launch FileZilla Pro and connect to your server using SFTP using SSH2 with a username and an empty password. Don't forget to close pageant when you're done.
So, for example, if you were using SSH-keys to gain access to an SFTP server, the public key would be shared with the server. That key is compared to the server's stored key for that username, which would have been stored on the server in advance. If the keys match, the user gains access.
Probably every SFTP/SSH library supports public key authentication.
For example:
SSH.NET (NuGet package):
var privateKey = new PrivateKeyFile(@"C:\some\path\key.pem");
var client = new SftpClient("example.com", "username", new[] { privateKey });
client.Connect();
If the private key is encrypted:
var privateKey = new PrivateKeyFile(@"C:\some\path\key.pem", "passphrase");
WinSCP .NET assembly (NuGet package):
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "example.com",
UserName = "username",
SshHostKeyFingerprint = "ssh-rsa 2048 ...=",
SshPrivateKeyPath = @"C:\some\path\key.ppk",
};
using (Session session = new Session())
{
session.Open(sessionOptions);
// Your code
}
WinSCP needs the key converted to PPK format (You can use WinSCP GUI for that, or PuTTYgen). Also note that WinSCP verifies the SSH host key (SshHostKeyFingerprint
). SSH.NET fails to do that by default, what is a security flaw.
If the private key is encrypted, add PrivateKeyPassphrase
or SecurePrivateKeyPassphrase
.
WinSCP GUI can generate a code template for you.
(I'm the author of the library)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With