How to use SFTP (with server validation - automatic)

The topic How to use SFTP (with server validation - known hosts) explains how the known_hosts file is used to validate the server being connected to.

Typically, the known_hosts file is generated when a command-line client first connects to a server - a prompt asks if the server should be added to the list of known hosts. This behavior can be produced in edtFTPj/PRO as follows:

The SSHFTPValidator class loads and caches the known hosts in memory. To automatically add a new host's public key when connecting, it is necessary to subclass SSHFTPValidator, and assign a new instance to SSHFTPClient.

The key method to override is the validate method. A boolean is passed in together with the server's hostname/IP address and the server's public key. The boolean indicates if the server has been found in the cached known hosts list. If it has not been found, it can at this point be added. An example is shown below:

class MyServerValidator extends SSHFTPValidator {
  protected boolean validate(String hostSpecifier, SSHFTPPublicKey publicKey, boolean hostKnown) {
    if (!hostKnown) {
      try {
        addKnownHost(hostSpecifier, publicKey);
      }
      catch (Exception ex) {
        log.error("Failed to add host '" + hostSpecifier + "' to known hosts", ex);
      }
    }
    return true;
  }
} 

To set the new validator, use the setValidator() method, as shown below:

ftp.setValidator( new MyServerValidator() ); 

To save the cached known hosts to the known_hosts file, use the saveKnownHosts method, as shown below:

ftp.getValidator().saveKnownHosts(); 

Note that it is not recommended to automatically add server public keys to the known_hosts file when connecting, as this removes an important part of SSH security - server validation. Instead, there should always be a review process - typically a dialog box presented to the user asking them to confirm if the key should be added. This simple example is presented to show how the mechanism works.