Class SCPClient

java.lang.Object
com.enterprisedt.net.ftp.ssh.SCPClient
Direct Known Subclasses:
SSHFTPClient

public class SCPClient extends Object
SCPClient implements SCP (SSH secure copy).

Connections are established when the connect() is invoked. Before it is called, the remote host must be defined, and host verification and client authentication should be configured.

Host Validation is the process of verifying that a host that is being connected to is the host that was requested. Host validation is done through an instance of SSHFTPValidator or a subclass thereof. By default, SCPClient, has an instance of this class that is available by means of the getValidator() method. Unless specialized validation functionality is required, initialization of validation functionality may be done simply by invoking methods on this object.

There are four approaches to setting up host validation:

  1. Disabling host validation. In general this represents a security weakness and should therefore be used only when testing code. This mode is selected as follows:
       ftpClient.getValidator().setHostValidationEnabled(false); 
     
  2. Initialize from a hosts file: A list of known hosts and their public keys are loaded from a file. The format of the file is similar to that used in OpenSSH. Each line contains the name of a host, the type of key it has, and its key (in base-64 printable form). For example:
     jackspc ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIE...
     
    If there are more than one host using a given key the host-name may be replaced by a comma-separated list of host-names. Wildcards may not be used. A host-file is loaded as follows:
       ftpClient.getValidator().loadKnownHosts("~/.ssh/known_hosts");
     
  3. Initialize programmatically: Host public keys may be loaded from individual files as follows:
       ftpClient.getValidator().addKnownHost("host1pk.pub");
       ftpClient.getValidator().addKnownHost("host2pk.pub");
     
    Public keys should be in OpenSSH or SECSH format.

Client Authentication is the method used by the server to authenticate clients. Different servers will enforce different policies for authenticating clients. SCPClient currently offers two authentication methods:

  1. User-name/Password Authentication involves simply passing a user-name/password to the server for authentication. This is set up simply by by calling setAuthentication as follows:
       ftpClient.setAuthentication("jack", "my_ftp_password");
     
  2. Public Key Authentication involves using a private/public key pair to authenticate the client. The key pair must be in a file in OpenSSH or SECSH format and the name is passed as follows:
       ftpClient.setAuthentication("myprivatekey", "jack", "my_keyfile_password");
     
    The user-name is the name of the user on the SFTP server, but the passphrase is the password for the key-file (if there is a password).
Version:
$Revision$
Author:
Bruce Blackshaw
  • Field Details

    • DEFAULT_PORT

      public static final int DEFAULT_PORT
      Default SSH port.
      See Also:
    • ssh

      protected com.enterprisedt.net.j2ssh.SshClient ssh
      J2SSH SshClient instance.
    • connProps

      protected com.enterprisedt.net.j2ssh.configuration.SshConnectionProperties connProps
      J2SSH SshConnectionProperties instance.
    • validator

      protected SSHFTPValidator validator
      Encapsulation and extension of J2SSH AbstractKnownHostsKeyVerification.
    • authenticator

      protected com.enterprisedt.net.j2ssh.authentication.SshAuthenticationClient authenticator
      J2SSH authenticator.
    • retryAuthenticator

      protected com.enterprisedt.net.j2ssh.authentication.SshAuthenticationClient retryAuthenticator
      J2SSH authenticator.
    • id

      protected String id
      Id of instance
    • downloadCount

      protected int downloadCount
      Count of downloaded files
    • uploadCount

      protected int uploadCount
      Count of uploaded files
    • deleteCount

      protected int deleteCount
      Count of deleted files
    • license

      protected com.enterprisedt.util.license.LicensePropertiesBase license
      The license details
    • proxySettings

      protected ProxySettings proxySettings
      The proxy settings
  • Constructor Details

    • SCPClient

      public SCPClient()
      Constructs an SCP client. The class description describes how to use the SCP client to obtain a connection with a remote host.
  • Method Details

    • setConnectionProperties

      public void setConnectionProperties(com.enterprisedt.net.j2ssh.configuration.SshConnectionProperties props)
      This method is not for public use. Please don't use it!
    • getConnectionProperties

      public com.enterprisedt.net.j2ssh.configuration.SshConnectionProperties getConnectionProperties()
      This method is not for public use. Please don't use it!
    • getId

      public String getId()
      Get the identifying string for this instance
    • setId

      public void setId(String id)
      Set the identifying string for this instance
      Parameters:
      id - identifying string
    • system

      public String system() throws FTPException, IOException
      Get a string representing the remote system.
      Returns:
      system string
      Throws:
      FTPException
      IOException
    • getDownloadCount

      public int getDownloadCount()
      Get the number of files downloaded since the count was reset
      Returns:
      download file count
    • resetDownloadCount

      public void resetDownloadCount()
      Reset the count of downloaded files to zero.
    • getUploadCount

      public int getUploadCount()
      Get the number of files uploaded since the count was reset
      Returns:
      upload file count
    • resetUploadCount

      public void resetUploadCount()
      Reset the count of uploaded files to zero.
    • getDeleteCount

      public int getDeleteCount()
      Get the number of files deleted since the count was reset
      Returns:
      deleted file count
    • resetDeleteCount

      public void resetDeleteCount()
      Reset the count of deleted files to zero.
    • getValidator

      public SSHFTPValidator getValidator()
      Returns a reference to the current host validator. By default this is an instance of SSHFTPValidator. If customized host validation is required then setValidator() should be used to set up the client to use a subclass of SSHFTPValidator.
      Returns:
      Returns the host validator.
    • setValidator

      public void setValidator(SSHFTPValidator validator) throws FTPException
      Sets the host validator. By default this is set to an instance of SSHFTPValidator. If customized host validation is required then this method should be used to set up the client to use a subclass of SSHFTPValidator.
      Parameters:
      validator - The host validator to set.
      Throws:
      FTPException
    • getHostPublicKey

      public static SSHFTPPublicKey getHostPublicKey(String remoteHost) throws FTPException
      Helper method that may be used to obtain a server's public key without instantiating an SCPClient. This method returns an SSHFTPPublicKey object whose SSHFTPPublicKey.write(OutputStream, int) method may be used to write the public key to a file. The method will return null if a public key could not be retrieved. Logging may be used to discover any connection problems. If more advanced settings are required then an instance of SCPClient should be used.
      Parameters:
      remoteHost - Address of the server whose public key is to be fetched.
      Returns:
      An instance of SSHFTPPublicKey representing
      Throws:
      FTPException
    • getHostPublicKey

      public static SSHFTPPublicKey getHostPublicKey(String remoteHost, int remotePort) throws FTPException
      Helper method that may be used to obtain a server's public key without instantiating an SCPClient. This method returns an SSHFTPPublicKey object SSHFTPPublicKey.write(OutputStream,int) method may be used to write the public key to a file. The method will return null if a public key could not be retrieved. Logging may be used to discover any connection problems. If more advanced settings are required then an instance of SCPClient should be used.
      Parameters:
      remoteHost - Address of the server whose public key is to be fetched.
      remotePort - Port of the server whose public key is to be fetched.
      Returns:
      An instance of SSHFTPPublicKey representing
      Throws:
      FTPException
    • getHostPublicKey

      public SSHFTPPublicKey getHostPublicKey()
      Provides access to the current server's public key. This member is only valid after an attempt has been made to connect to the server. It is null before the first connection attempt is made.

      This method is particularly useful if the server's public key is not available by other means. In such cases a connection attempt should be made without adding any known hosts. This attempt will fail, but getHostPublicKey() may be used afterwards to obtain the public key. The SSHFTPPublicKey.write(OutputStream,int) method may be used to write it to a file for use in subsequent connections.

      Note that null may be returned after a connection attempt is made if the attempt failed before public keys were exchanged between the client and the server.

      Returns:
      Returns the server's public key.
    • setAuthentication

      public void setAuthentication(String userName, String password) throws FTPException
      Set up user-name/password authentication. The user-name and password must be recognized by the SFTP server. This method must be called before an attempt to connect to the SFTP server is made (i.e. before the connect method is invoked). This method first attempts to use password authentication, and if that fails, falls back to keyboard-interactive authentication via password
      Parameters:
      userName - User-name as set up on the SFTP server.
      password - Password as set up on the SFTP server.
      Throws:
      FTPException - Thrown if an SFTP-related error occurs.
    • setAuthentication

      public void setAuthentication(String userName, String password, PasswordChanger pwdChanger) throws FTPException
      Set up user-name/password authentication. The user-name and password must be recognized by the SFTP server. This method must be called before an attempt to connect to the SFTP server is made (i.e. before the connect method is invoked). This method first attempts to use password authentication, and if that fails, falls back to keyboard-interactive authentication via password
      Parameters:
      userName - User-name as set up on the SFTP server.
      password - Password as set up on the SFTP server.
      pwdChanger - instance that gets new password
      Throws:
      FTPException - Thrown if an SFTP-related error occurs.
    • setAuthenticationChangePassword

      public void setAuthenticationChangePassword(String userName, String oldPassword, String newPassword) throws FTPException
      Set up user-name/password authentication, and change the user's password. The user-name and old password must be recognized by the SFTP server. This method must be called before an attempt to connect to the SFTP server is made (i.e. before the connect method is invoked).
      Parameters:
      userName - User-name as set up on the SFTP server.
      oldPassword - Password as set up on the SFTP server.
      newPassword - new password to set
      Throws:
      FTPException - Thrown if an SFTP-related error occurs.
    • setAuthentication

      public void setAuthentication(String user, SSHAuthPrompt[] prompts) throws FTPException
      Set up keyboard-interactive (KBI) authentication by supplying an array of responses to possible prompts by the SSH server
      Parameters:
      user - user to login as
      prompts - prompt responses supplied to pass the server authentication prompts
      Throws:
      FTPException
    • setAuthentication

      public void setAuthentication(String keyFileName, String userName, String keyFilePassphrase) throws IOException, FTPException
      Set up the SFTP client to authenticate using a private/public key-pair. The private key is loaded from a file. The SFTP server must have been set up with the public key before this authentication method is used. This method must be called before an attempt to connect to the SFTP server is made (i.e. before the connect method is invoked).

      The key-file can be in either OpenSSH format (generated by default by ssh-keygen) or SECSH format.

      The file may or may not be password protected depending on how it was generated.

      Parameters:
      keyFileName - File containing the private key.
      userName - User-name as set up on the server.
      keyFilePassphrase - (Optional) Key-file passphrase.
      Throws:
      IOException - Thrown if the key-file could not be read.
      SSHFTPException - Thrown if an SFTP-related error occurred.
      FTPException
    • setAuthentication

      public void setAuthentication(InputStream inStr, String userName, String keyFilePassphrase) throws IOException, FTPException
      Set up the SFTP client to authenticate using a private/public key-pair. The private key is loaded from an input-stream. The SFTP server must have been set up with the public key before this authentication method is used. This method must be called before an attempt to connect to the SFTP server is made (i.e. before the connect method is invoked).

      The key-file can be in either OpenSSH format (generated by default by ssh-keygen) or SECSH format.

      The file may or may not be password protected depending on how it was generated.

      Parameters:
      inStr - InputStream containing the private key.
      userName - User-name as set up on the server.
      keyFilePassphrase - (Optional) Key-file passphrase.
      Throws:
      IOException - Thrown if the key-file could not be read.
      SSHFTPException - Thrown if an SFTP-related error occurred.
      FTPException
    • setAuthentication

      public void setAuthentication(String keyFileName, String userName, String keyFilePassphrase, String userPassword) throws IOException, FTPException
      Set up the SFTP client to authenticate using a private/public key-pair, followed by password authentication. The private key is loaded from a file. The SFTP server must have been set up with the public key before this authentication method is used. This method must be called before an attempt to connect to the SFTP server is made (i.e. before the connect method is invoked).

      The key-file can be in either OpenSSH format (generated by default by ssh-keygen) or SECSH format.

      The file may or may not be password protected depending on how it was generated.

      Parameters:
      keyFileName - File containing the private key.
      userName - User-name as set up on the server.
      keyFilePassphrase - (Optional) Key-file passphrase.
      userPassword - User's password
      Throws:
      IOException - Thrown if the key-file could not be read.
      SSHFTPException - Thrown if an SFTP-related error occurred.
      FTPException
    • setAuthentication

      public void setAuthentication(String keyFileName, String userName, String keyFilePassphrase, String userPassword, boolean publicKeyFirst) throws IOException, FTPException
      Set up the SFTP client to authenticate using a private/public key-pair, followed by password authentication, or in the reverse order. The private key is loaded from a file. The SFTP server must have been set up with the public key before this authentication method is used. This method must be called before an attempt to connect to the SFTP server is made (i.e. before the connect method is invoked).

      The key-file can be in either OpenSSH format (generated by default by ssh-keygen) or SECSH format.

      The file may or may not be password protected depending on how it was generated.

      Parameters:
      keyFileName - File containing the private key.
      userName - User-name as set up on the server.
      keyFilePassphrase - (Optional) Key-file passphrase.
      userPassword - User's password
      publicKeyFirst - if true, public key then private key, if false the reverse
      Throws:
      IOException - Thrown if the key-file could not be read.
      SSHFTPException - Thrown if an SFTP-related error occurred.
      FTPException
    • validateAlgorithms

      protected void validateAlgorithms() throws SSHFTPException
      Check to see if at least one of each type of algorithm is enabled.
      Throws:
      SSHFTPException - Thrown if one algorithm-type has no enabled algorithms.
    • getEnabledAlgorithms

      public SSHFTPAlgorithm[] getEnabledAlgorithms()
      Returns an array containing all enabled algorithms (of all types).
      Returns:
      An array of all enabled algorithms.
    • getEnabledAlgorithms

      public SSHFTPAlgorithm[] getEnabledAlgorithms(int algorithmType) throws SSHFTPException
      Returns an array containing all enabled algorithms of a particular type.
      Parameters:
      algorithmType - Type of algorithms to return (See SSHFTPAlgorithm).
      Returns:
      An array of all enabled algorithms of the given type.
      Throws:
      SSHFTPException - Thrown if the given algorithm-type is invalid.
    • disableAllAlgorithms

      public void disableAllAlgorithms(int algorithmType) throws SSHFTPException
      Disables all algorithms of a particular type. Note that one algorithm of each type must be enabled before you can connect to a server. This removes the default preferred algorithm for the type, so that it is no longer inserted at the beginning of the list of algorithms of this type sent to the server.
      Parameters:
      algorithmType - Type of algorithms to return (See SSHFTPAlgorithm).
      Throws:
      SSHFTPException
    • disableAllAlgorithms

      public void disableAllAlgorithms()
      Disables all algorithms. Note that one algorithm of each type must be enabled before you can connect to a server. This removes all default preferred algorithms so that they are no longer inserted at the beginning of the list of algorithms sent to the server.
    • setAlgorithmEnabled

      public void setAlgorithmEnabled(SSHFTPAlgorithm algorithm, boolean enable)
      Enable/disable the given algorithm.
      Parameters:
      algorithm - Algorithm to enable/disable.
      enable - Flag indicating whether the algorithm should be enabled or disabled.
    • isAlgorithmEnabled

      public boolean isAlgorithmEnabled(SSHFTPAlgorithm algorithm)
      Returns true if the given algorithm is enabled.
      Parameters:
      algorithm - Algorithm to return status of.
    • getRemoteHost

      public String getRemoteHost()
    • setRemoteHost

      public void setRemoteHost(String remoteHost) throws FTPException
      Throws:
      FTPException
    • getRemotePort

      public int getRemotePort()
      Returns the SSH port of the remote host. The default is 22.
      Returns:
      Returns the SSH port of the remote host.
    • setRemotePort

      public void setRemotePort(int port) throws FTPException
      Set the SSH port of the remote host. This may only be done if the client is not already connected to the server. The default is 22.
      Parameters:
      port - The port to set.
      Throws:
      FTPException - Thrown if the client is already connected to the server.
    • getProxySettings

      public ProxySettings getProxySettings()
      Get the proxy settings instance. Its properties can be set to use proxies.
      Returns:
      ProxySettings
    • setProxyParams

      public void setProxyParams(ProxyParameters params)
      Deprecated.
      Setup the parameters required for using a proxy
      Parameters:
      params - parameter object
    • setTransportProvider

      public void setTransportProvider(int provider)
      Deprecated.
      Set the type of transport provider to use. Default is standard sockets
      Parameters:
      provider - provider integer
    • getTransportProvider

      public int getTransportProvider()
      Deprecated.
      Get the currently set transport provider
      Returns:
      int
    • getTimeout

      public int getTimeout()
    • setTimeout

      public void setTimeout(int millis) throws FTPException
      Throws:
      FTPException
    • getNetworkBufferSize

      public int getNetworkBufferSize()
      Get the size of the network buffers (SO_SNDBUF and SO_RCVBUF).
      Returns:
      int
    • setNetworkBufferSize

      public void setNetworkBufferSize(int networkBufferSize)
      Set the size of the network buffers (SO_SNDBUF and SO_RCVBUF).
      Parameters:
      networkBufferSize - new buffer size to set
    • isRekeyEnabled

      public boolean isRekeyEnabled()
      Is re-keying after 1 GB enabled? If enabled (the default), after 1 GB of transfer a new set of cryptographic keys are established. This is a security measure, not supported by all servers.
      Returns:
      true if enabled (the default)
    • setRekeyEnabled

      public void setRekeyEnabled(boolean enableRekey)
      Set flag to disable or enable re-keying after 1 GB
      Parameters:
      enableRekey - true to enable, false to disable
    • setRekeyTransferLimit

      public void setRekeyTransferLimit(long kilobytes) throws IOException
      Set a different limit to the 1 GB default
      Parameters:
      kilobytes - new limit in kB
      Throws:
      IOException
    • connect

      public void connect() throws IOException, FTPException
      Connects to the server at the address and port number defined in the constructor. Please refer to the class description for information on configuration steps that must be taken before this method is called.
      Throws:
      IOException - Thrown if there is a TCP/IP-related error.
      FTPException - Thrown if client is already connected or if there is a configuration error, or if a connection could not be established.
    • connectSSH

      protected void connectSSH() throws IOException, FTPException
      Connects to the server at the address and port number defined in the constructor. Please refer to the class description for information on configuration steps that must be taken before this method is called.
      Throws:
      IOException - Thrown if there is a TCP/IP-related error.
      FTPException - Thrown if client is already connected or if there is a configuration error, or if a connection could not be established.
    • executeCommand

      public String executeCommand(String command, boolean allocatePseudoTerminal) throws FTPException, IOException
      Execute a command on the remote server. This opens a new session channel to execute the command. Optionally, a pseudoterminal can be allocated on the channel.
      Parameters:
      command - command to execute
      allocatePseudoTerminal - true if a pseudoterminal is be to allocated prior to executing the command
      Returns:
      string with the command output
      Throws:
      FTPException
      IOException
    • executeCommand

      public String executeCommand(String command) throws FTPException, IOException
      Execute a command on the remote server. This opens a new session channel to execute the command. No pseudoterminal is created.
      Parameters:
      command - command to execute
      Returns:
      string with the command output
      Throws:
      FTPException
      IOException
    • checkConnection

      protected void checkConnection(boolean shouldBeConnected) throws FTPException
      Checks if the client has connected to the server and throws an exception if it hasn't. This is only intended to be used by subclasses
      Throws:
      FTPException - Thrown if the client has not connected to the server.
    • connected

      public boolean connected()
      Is the client currently connected?
      Returns:
      true if connected, false otherwise
    • put

      public String put(String localPath, String remoteFile) throws IOException, FTPException
      Upload a file.
      Parameters:
      localPath - path of local file to be uploaded
      remoteFile - path of remote file to upload to
      Throws:
      IOException
      FTPException
    • get

      public void get(String localPath, String remoteFile) throws IOException, FTPException
      Download a file
      Parameters:
      localPath - path of local file to download to
      remoteFile - path of remote file
      Throws:
      IOException
      FTPException
    • quit

      public void quit() throws IOException, FTPException
      Throws:
      IOException
      FTPException
    • quitImmediately

      public void quitImmediately() throws IOException, FTPException
      Throws:
      IOException
      FTPException
    • toString

      public String toString()
      String representation
      Overrides:
      toString in class Object