Class SCPClient
- Direct Known Subclasses:
SSHFTPClient
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:
- 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);
- 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"); - 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:
- User-name/Password Authentication involves simply passing a
user-name/password to the server for authentication. This is set up simply by
by calling
setAuthenticationas follows:ftpClient.setAuthentication("jack", "my_ftp_password"); - 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 Summary
FieldsModifier and TypeFieldDescriptionprotected com.enterprisedt.net.j2ssh.authentication.SshAuthenticationClientJ2SSH authenticator.protected com.enterprisedt.net.j2ssh.configuration.SshConnectionPropertiesJ2SSH SshConnectionProperties instance.static final intDefault SSH port.protected intCount of deleted filesprotected intCount of downloaded filesprotected StringId of instanceprotected com.enterprisedt.util.license.LicensePropertiesBaseThe license detailsprotected ProxySettingsThe proxy settingsprotected com.enterprisedt.net.j2ssh.authentication.SshAuthenticationClientJ2SSH authenticator.protected com.enterprisedt.net.j2ssh.SshClientJ2SSH SshClient instance.protected intCount of uploaded filesprotected SSHFTPValidatorEncapsulation and extension of J2SSHAbstractKnownHostsKeyVerification. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected voidcheckConnection(boolean shouldBeConnected) Checks if the client has connected to the server and throws an exception if it hasn't.voidconnect()Connects to the server at the address and port number defined in the constructor.booleanIs the client currently connected?protected voidConnects to the server at the address and port number defined in the constructor.voidDisables all algorithms.voiddisableAllAlgorithms(int algorithmType) Disables all algorithms of a particular type.executeCommand(String command) Execute a command on the remote server.executeCommand(String command, boolean allocatePseudoTerminal) Execute a command on the remote server.voidDownload a filecom.enterprisedt.net.j2ssh.configuration.SshConnectionPropertiesThis method is not for public use.intGet the number of files deleted since the count was resetintGet the number of files downloaded since the count was resetReturns an array containing all enabled algorithms (of all types).getEnabledAlgorithms(int algorithmType) Returns an array containing all enabled algorithms of a particular type.Provides access to the current server's public key.static SSHFTPPublicKeygetHostPublicKey(String remoteHost) Helper method that may be used to obtain a server's public key without instantiating anSCPClient.static SSHFTPPublicKeygetHostPublicKey(String remoteHost, int remotePort) Helper method that may be used to obtain a server's public key without instantiating anSCPClient.getId()Get the identifying string for this instanceintGet the size of the network buffers (SO_SNDBUF and SO_RCVBUF).Get the proxy settings instance.intReturns the SSH port of the remote host.intintDeprecated.intGet the number of files uploaded since the count was resetReturns a reference to the current host validator.booleanisAlgorithmEnabled(SSHFTPAlgorithm algorithm) Returnstrueif the given algorithm is enabled.booleanIs re-keying after 1 GB enabled? If enabled (the default), after 1 GB of transfer a new set of cryptographic keys are established.Upload a file.voidquit()voidvoidReset the count of deleted files to zero.voidReset the count of downloaded files to zero.voidReset the count of uploaded files to zero.voidsetAlgorithmEnabled(SSHFTPAlgorithm algorithm, boolean enable) Enable/disable the given algorithm.voidsetAuthentication(InputStream inStr, String userName, String keyFilePassphrase) Set up the SFTP client to authenticate using a private/public key-pair.voidsetAuthentication(String user, SSHAuthPrompt[] prompts) Set up keyboard-interactive (KBI) authentication by supplying an array of responses to possible prompts by the SSH servervoidsetAuthentication(String userName, String password) Set up user-name/password authentication.voidsetAuthentication(String userName, String password, PasswordChanger pwdChanger) Set up user-name/password authentication.voidsetAuthentication(String keyFileName, String userName, String keyFilePassphrase) Set up the SFTP client to authenticate using a private/public key-pair.voidsetAuthentication(String keyFileName, String userName, String keyFilePassphrase, String userPassword) Set up the SFTP client to authenticate using a private/public key-pair, followed by password authentication.voidsetAuthentication(String keyFileName, String userName, String keyFilePassphrase, String userPassword, boolean publicKeyFirst) Set up the SFTP client to authenticate using a private/public key-pair, followed by password authentication, or in the reverse order.voidsetAuthenticationChangePassword(String userName, String oldPassword, String newPassword) Set up user-name/password authentication, and change the user's password.voidsetConnectionProperties(com.enterprisedt.net.j2ssh.configuration.SshConnectionProperties props) This method is not for public use.voidSet the identifying string for this instancevoidsetNetworkBufferSize(int networkBufferSize) Set the size of the network buffers (SO_SNDBUF and SO_RCVBUF).voidsetProxyParams(ProxyParameters params) Deprecated.voidsetRekeyEnabled(boolean enableRekey) Set flag to disable or enable re-keying after 1 GBvoidsetRekeyTransferLimit(long kilobytes) Set a different limit to the 1 GB defaultvoidsetRemoteHost(String remoteHost) voidsetRemotePort(int port) Set the SSH port of the remote host.voidsetTimeout(int millis) voidsetTransportProvider(int provider) Deprecated.voidsetValidator(SSHFTPValidator validator) Sets the host validator.system()Get a string representing the remote system.toString()String representationprotected voidCheck to see if at least one of each type of algorithm is enabled.
-
Field Details
-
DEFAULT_PORT
public static final int DEFAULT_PORTDefault SSH port.- See Also:
-
ssh
protected com.enterprisedt.net.j2ssh.SshClient sshJ2SSH SshClient instance. -
connProps
protected com.enterprisedt.net.j2ssh.configuration.SshConnectionProperties connPropsJ2SSH SshConnectionProperties instance. -
validator
Encapsulation and extension of J2SSHAbstractKnownHostsKeyVerification. -
authenticator
protected com.enterprisedt.net.j2ssh.authentication.SshAuthenticationClient authenticatorJ2SSH authenticator. -
retryAuthenticator
protected com.enterprisedt.net.j2ssh.authentication.SshAuthenticationClient retryAuthenticatorJ2SSH authenticator. -
id
Id of instance -
downloadCount
protected int downloadCountCount of downloaded files -
uploadCount
protected int uploadCountCount of uploaded files -
deleteCount
protected int deleteCountCount of deleted files -
license
protected com.enterprisedt.util.license.LicensePropertiesBase licenseThe license details -
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
Get the identifying string for this instance -
setId
Set the identifying string for this instance- Parameters:
id- identifying string
-
system
Get a string representing the remote system.- Returns:
- system string
- Throws:
FTPExceptionIOException
-
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
Returns a reference to the current host validator. By default this is an instance ofSSHFTPValidator. If customized host validation is required thensetValidator()should be used to set up the client to use a subclass ofSSHFTPValidator.- Returns:
- Returns the host validator.
-
setValidator
Sets the host validator. By default this is set to an instance ofSSHFTPValidator. If customized host validation is required then this method should be used to set up the client to use a subclass ofSSHFTPValidator.- Parameters:
validator- The host validator to set.- Throws:
FTPException
-
getHostPublicKey
Helper method that may be used to obtain a server's public key without instantiating anSCPClient. This method returns anSSHFTPPublicKeyobject whoseSSHFTPPublicKey.write(OutputStream, int)method may be used to write the public key to a file. The method will returnnullif 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 ofSCPClientshould be used.- Parameters:
remoteHost- Address of the server whose public key is to be fetched.- Returns:
- An instance of
SSHFTPPublicKeyrepresenting - 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 anSCPClient. This method returns anSSHFTPPublicKeyobjectSSHFTPPublicKey.write(OutputStream,int)method may be used to write the public key to a file. The method will returnnullif 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 ofSCPClientshould 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
SSHFTPPublicKeyrepresenting - Throws:
FTPException
-
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 isnullbefore 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. TheSSHFTPPublicKey.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
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 theconnectmethod 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 theconnectmethod 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 theconnectmethod 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
Set up keyboard-interactive (KBI) authentication by supplying an array of responses to possible prompts by the SSH server- Parameters:
user- user to login asprompts- 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 theconnectmethod 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 theconnectmethod 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-InputStreamcontaining 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 theconnectmethod 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 theconnectmethod 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 passwordpublicKeyFirst- 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
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
Returns an array containing all enabled algorithms (of all types).- Returns:
- An array of all enabled algorithms.
-
getEnabledAlgorithms
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
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
Enable/disable the given algorithm.- Parameters:
algorithm- Algorithm to enable/disable.enable- Flag indicating whether the algorithm should be enabled or disabled.
-
isAlgorithmEnabled
Returnstrueif the given algorithm is enabled.- Parameters:
algorithm- Algorithm to return status of.
-
getRemoteHost
-
setRemoteHost
- 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
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
Get the proxy settings instance. Its properties can be set to use proxies.- Returns:
- ProxySettings
-
setProxyParams
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
- 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
Set a different limit to the 1 GB default- Parameters:
kilobytes- new limit in kB- Throws:
IOException
-
connect
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
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 executeallocatePseudoTerminal- true if a pseudoterminal is be to allocated prior to executing the command- Returns:
- string with the command output
- Throws:
FTPExceptionIOException
-
executeCommand
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:
FTPExceptionIOException
-
checkConnection
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
Upload a file.- Parameters:
localPath- path of local file to be uploadedremoteFile- path of remote file to upload to- Throws:
IOExceptionFTPException
-
get
Download a file- Parameters:
localPath- path of local file to download toremoteFile- path of remote file- Throws:
IOExceptionFTPException
-
quit
- Throws:
IOExceptionFTPException
-
quitImmediately
- Throws:
IOExceptionFTPException
-
toString
String representation
-
getProxySettings()