edtFTPnet/PRO - Secure FTP component for .NET | Free Trial | Pricing

How to use SFTP (generating known hosts file)

Sometimes a known_hosts file will not exist and must be generated.

A third party SSH client will normally generate this file simply by connecting to the remote host, commonly writing it to a .ssh directory.

Alternatively, it can be generated programmatically by edtFTPnet/PRO, again by attempting to connect.

To do this, ServerValidation must be set to Callback:

SecureFTPConnection conn = new SecureFTPConnection(); // or similar
conn.ServerValidation = SecureFTPServerValidationType.Callback;

A callback function must be written that writes the public key to the known_hosts file:

private void SavePublicKeyToKnownHosts(object sender, ServerValidationEventArgs e)
{
	if (!e.IsValid) // i.e. not in current known hosts
	{
		conn.KnownHosts.AddHostKey(conn.ServerAddress, e.SSHPublicKey);
		conn.KnownHosts.WriteKnownHosts("D:\\temp\\known_hosts");
		e.IsValid = true;
	}
} 

The function above must have access to the SecureFTPConnection object, or at least the KnownHosts property. The public key of the SSH server is a property of the ServerValidationEventArgs object, as is the IsValid property. The key is added to the KnownHostsManager, and then written to file.

Note that IsValid is set to true after writing the file - without this the connection to the server will fail.

For this function to be called, it must be tied to the ValidatingServer event:

conn.ValidatingServer += 
  new EnterpriseDT.Net.Ftp.ServerValidationHandler(SavePublicKeyToKnownHosts);

The connect() method must called, and the client will attempt to connect to the SFTP server. As part of the connect sequence, the server's public key is sent to the client, and at this point the user-defined callback is invoked, writing the public key to the set file.