Class SshClient


  • public class SshClient
    extends java.lang.Object

    Implements an SSH client with methods to connect to a remote server and perform all necersary SSH functions such as SCP, SFTP, executing commands, starting the users shell and perform port forwarding.

    There are several steps to perform prior to performing the desired task. This involves the making the initial connection, authenticating the user and creating a session to execute a command, shell or subsystem and/or configuring the port forwarding manager.

    To create a connection use the following code:

     // Create a instance and connect SshClient
     ssh = new SshClient();
     ssh.connect("hostname");
     
    Once this code has executed and returned the connection is ready for authentication:
     PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
     pwd.setUsername("foo");
     pwd.setPassword("xxxxx");
     // Authenticate the user
     int result = ssh.authenticate(pwd);
     if(result==AuthenticationProtocolState.COMPLETED) {
        // Authentication complete
     }
     
    Once authenticated the user's shell can be started:
     // Open a session channel
     SessionChannelClient session =
                          ssh.openSessionChannel();
    
     // Request a pseudo terminal, if you do not you may not see the prompt
     if(session.requestPseudoTerminal("ansi", 80, 24, 0, 0, "") {
          // Start the users shell
          if(session.startShell()) {
             // Do something with the session output
             session.getOutputStream().write("echo message\n");
             ....
           }
     }
     

    Since:
    0.2.0
    Version:
    $Revision: 1.75 $
    Author:
    Lee David Painter
    • Field Detail

      • authentication

        protected AuthenticationProtocolClient authentication
        The SSH Authentication protocol implementation for this SSH client. The SSH Authentication protocol runs over the SSH Transport protocol as a transport protocol service.
      • connection

        protected ConnectionProtocol connection
        The SSH Connection protocol implementation for this SSH client. The connection protocol runs over the SSH Transport protocol as a transport protocol service and is started by the authentication protocol after a successful authentication.
      • forwarding

        protected ForwardingClient forwarding
        Provides a high level management interface for SSH port forwarding.
      • transport

        protected TransportProtocolClient transport
        The SSH Transport protocol implementation for this SSH Client.
      • authenticationState

        protected int authenticationState
        The current state of the authentication for the current connection.
      • socketTimeout

        protected int socketTimeout
        The timeout in milliseconds for the underlying transport provider (typically a Socket).
      • eventHandler

        protected SshEventAdapter eventHandler
        A Transport protocol event handler instance that receives notifications of transport layer events such as Socket timeouts and disconnection.
      • activeChannels

        protected java.util.Vector activeChannels
        The currently active channels for this SSH Client connection.
      • activeChannelListener

        protected com.sshtools.j2ssh.SshClient.ActiveChannelEventListener activeChannelListener
        An channel event listener implemention to maintain the active channel list.
      • useDefaultForwarding

        protected boolean useDefaultForwarding
        Flag indicating whether the forwarding instance is created when the connection is made.
    • Constructor Detail

      • SshClient

        public SshClient()

        Contructs an unitilialized SshClient ready for connecting.

    • Method Detail

      • getAuthenticationBanner

        public java.lang.String getAuthenticationBanner​(int timeout)
                                                 throws java.io.IOException

        Returns the server's authentication banner.

        In some jurisdictions, sending a warning message before authentication may be relevant for getting legal protection. Many UNIX machines, for example, normally display text from `/etc/issue', or use "tcp wrappers" or similar software to display a banner before issuing a login prompt.

        The server may or may not send this message. Call this method to retrieve the message, specifying a timeout limit to wait for the message.

        Parameters:
        timeout - The number of milliseconds to wait for the banner message before returning
        Returns:
        The server's banner message
        Throws:
        java.io.IOException - If an IO error occurs reading the message
        Since:
        0.2.0
      • getAvailableAuthMethods

        public java.util.List getAvailableAuthMethods​(java.lang.String username)
                                               throws java.io.IOException

        Returns the list of available authentication methods for a given user.

        A client may request a list of authentication methods that may continue by using the "none" authentication method.This method calls the "none" method and returns the available authentication methods.

        Parameters:
        username - The name of the account for which you require the available authentication methods
        Returns:
        A list of Strings, for example "password", "publickey" & "keyboard-interactive"
        Throws:
        java.io.IOException - If an IO error occurs during the operation
        Since:
        0.2.0
      • isConnected

        public boolean isConnected()

        Returns the connection state of the client.

        Returns:
        true if the client is connected, false otherwise
        Since:
        0.2.0
      • isAuthenticated

        public boolean isAuthenticated()

        Evaluate whether the client has successfully authenticated.

        Returns:
        true if the client is authenticated, otherwise false
      • getServerId

        public java.lang.String getServerId()

        Returns the identification string sent by the server during protocol negotiation. For example "SSH-2.0-OpenSSH_p3.4".

        Returns:
        The server's identification string.
        Since:
        0.2.0
      • getServerHostKey

        public SshPublicKey getServerHostKey()

        Returns the server's public key supplied during key exchange.

        Returns:
        the server's public key
        Since:
        0.2.0
      • getConnectionState

        public TransportProtocolState getConnectionState()

        Returns the transport protocol's connection state.

        Returns:
        The transport protocol's state
        Since:
        0.2.0
      • getForwardingClient

        public ForwardingClient getForwardingClient()

        Returns the default port forwarding manager.

        Returns:
        This connection's forwarding client
        Since:
        0.2.0
      • getRemoteEOL

        public int getRemoteEOL()

        Return's a rough guess at the server's EOL setting. This is simply derived from the identification string and should not be used as a cast iron proof on the EOL setting.

        Returns:
        The transport protocol's EOL constant
        Since:
        0.2.0
      • addEventHandler

        public void addEventHandler​(SshEventAdapter eventHandler)

        Set the event handler for the underlying transport protocol.

         ssh.setEventHandler(new TransportProtocolEventHandler() {
        
           public void onSocketTimeout(TransportProtocol transport) {
        // Do something to handle the socket timeout
        } public void onDisconnect(TransportProtocol transport) { // Perhaps some clean up? } });
        Parameters:
        eventHandler - The event handler instance to receive transport protocol events
        Since:
        0.2.0
        See Also:
        TransportProtocolEventHandler
      • setSocketTimeout

        public void setSocketTimeout​(int milliseconds)

        Set's the socket timeout (in milliseconds) for the underlying transport provider. This MUST be called prior to connect.

        SshClient ssh = new SshClient(); ssh.setSocketTimeout(30000); ssh.connect("hostname");
        Parameters:
        milliseconds - The number of milliseconds without activity before the timeout event occurs
        Since:
        0.2.0
      • getRemoteEOLString

        public java.lang.String getRemoteEOLString()

        Return's a rough guess at the server's EOL setting. This is simply derived from the identification string and should not be used as a cast iron proof on the EOL setting.

        Returns:
        The EOL string
        Since:
        0.2.0
      • getConnectionProperties

        public SshConnectionProperties getConnectionProperties()
        Get the connection properties for this connection.
        Returns:
      • authenticate

        public int authenticate​(SshAuthenticationClient auth)
                         throws java.io.IOException

        Authenticate the user on the remote host.

        To authenticate the user, create an SshAuthenticationClient instance and configure it with the authentication details.

        PasswordAuthenticationClient pwd = new PasswordAuthenticationClient(); pwd.setUsername("root"); pwd.setPassword("xxxxxxxxx"); int result = ssh.authenticate(pwd);

        The method returns a result value will one of the public static values defined in AuthenticationProtocolState. These are

        COMPLETED - The authentication succeeded.
        PARTIAL - The authentication succeeded but a further authentication method is required.
        FAILED - The authentication failed.
        CANCELLED - The user cancelled authentication (can only be returned when the user is prompted for information.

        Parameters:
        auth - A configured SshAuthenticationClient instance ready for authentication
        Returns:
        The authentication result
        Throws:
        java.io.IOException - If an IO error occurs during authentication
        Since:
        0.2.0
      • acceptsKey

        public boolean acceptsKey​(java.lang.String username,
                                  SshPublicKey key)
                           throws java.io.IOException

        Determine whether a private/public key pair will be accepted for public key authentication.

        When using public key authentication, the signing of data could take some time depending upon the available machine resources. By calling this method, you can determine whether the server will accept a key for authentication by providing the public key. The server will verify the key against the user's authorized keys and return true should the public key be authorized. The caller can then proceed with the private key operation.

        Parameters:
        username - The username for authentication
        key - The public key for which authentication will be attempted
        Returns:
        true if the server will accept the key, otherwise false
        Throws:
        java.io.IOException - If an IO error occurs during the operation
        SshException
        Since:
        0.2.0
      • connect

        public void connect​(java.lang.String hostname)
                     throws java.io.IOException

        Connect the client to the server using default connection properties.

        This call attempts to connect to the hostname specified on the standard SSH port of 22 and uses all the default connection properties. This call is the equivilent of calling:

         SshConnectionProperties properties = new
                                   SshConnectionProperties();
         properties.setHostname("hostname");
         ssh.connect(properties);
         
        Parameters:
        hostname - The hostname of the server to connect
        Throws:
        java.io.IOException - If an IO error occurs during the connect operation
        Since:
        0.2.0
        See Also:
        connect(com.sshtools.j2ssh.configuration.SshConnectionProperties)
      • connect

        public void connect​(java.lang.String hostname,
                            HostKeyVerification hosts)
                     throws java.io.IOException

        Connect the client to the server using the default connection properties.

        This call attempts to connect to the hostname specified on the standard SSH port of 22 and uses all the default connection properties. When this method returns the connection has been established, the server's identity been verified and the connection is ready for user authentication. Host key verification will be performed using the host key verification instance provided:

         // Connect and consult $HOME/.ssh/known_hosts
         ssh.connect("hostname", new ConsoleKnownHostsKeyVerification());
         // Connect and allow any host
         ssh.connect("hostname", new
                         IgnoreHostKeyVerification());
         

        You can provide your own host key verification process by implementing the HostKeyVerification interface.

        Parameters:
        hostname - The hostname of the server to connect
        hosts - The host key verification instance to consult for host key validation
        Throws:
        java.io.IOException - If an IO error occurs during the connect operation
        Since:
        0.2.0
        See Also:
        connect(com.sshtools.j2ssh.configuration.SshConnectionProperties, com.sshtools.j2ssh.transport.HostKeyVerification)
      • connect

        public void connect​(java.lang.String hostname,
                            int port)
                     throws java.io.IOException

        Connect the client to the server on a specified port with default connection properties.

        This call attempts to connect to the hostname and port specified. This call is the equivilent of calling:

        SshConnectionProperties properties = new SshConnectionProperties(); properties.setHostname("hostname"); properties.setPort(10022); ssh.connect(properties);
        Parameters:
        hostname - The hostname of the server to connect
        port - The port to connect
        Throws:
        java.io.IOException - If an IO error occurs during the connect operation
        Since:
        0.2.0
        See Also:
        connect(com.sshtools.j2ssh.configuration.SshConnectionProperties)
      • connect

        public void connect​(java.lang.String hostname,
                            int port,
                            HostKeyVerification hosts)
                     throws java.io.IOException

        Connect the client to the server on a specified port with default connection properties.

        This call attempts to connect to the hostname and port specified. When this method returns the connection has been established, the server's identity been verified and the connection is ready for user authentication. Host key verification will be performed using the host key verification instance provided:

         // Connect and consult $HOME/.ssh/known_hosts
         ssh.connect("hostname", new ConsoleKnownHostsKeyVerification());
         // Connect and allow any host
         ssh.connect("hostname", new
                         IgnoreHostKeyVerification());
         

        You can provide your own host key verification process by implementing the HostKeyVerification interface.

        Parameters:
        hostname - The hostname of the server to connect
        port - The port to connect
        hosts - The host key verification instance to consult for host key validation
        Throws:
        java.io.IOException - If an IO error occurs during the connect operation
        Since:
        0.2.0
        See Also:
        connect(com.sshtools.j2ssh.configuration.SshConnectionProperties, com.sshtools.j2ssh.transport.HostKeyVerification)
      • connect

        public void connect​(SshConnectionProperties properties)
                     throws java.io.IOException

        Connect the client to the server with the specified properties.

        This call attempts to connect to using the connection properties specified. When this method returns the connection has been established, the server's identity been verified and the connection is ready for user authentication. To use this method first create a properties instance and set the required fields.

         SshConnectionProperties properties = new
                                 SshConnectionProperties();
         properties.setHostname("hostname");
         properties.setPort(10022);
         properties.setPrefCSEncryption("blowfish-cbc");
         ssh.connect(properties);
         

        Host key verification will be performed using ConsoleKnownHostsKeyVerification and so this call is the equivilent of calling:

         ssh.connect("hostname", new ConsoleKnownHostsKeyVerification());
         

        If the key is not matched to any keys already in the $HOME/.ssh/known_hosts file, the user will be prompted via the console to confirm the identity of the remote server. The user will receive the following prompt.

        The host shell.sourceforge.net is currently unknown to the system The host key fingerprint is: 1024: 4c 68 3 d4 5c 58 a6 1d 9d 17 13 24 14 48 ba 99 Do you want to allow this host key? [Yes|No|Always]:

        Selecting the "always" option will write the key to the known_hosts file.

        Parameters:
        properties - The connection properties
        Throws:
        java.io.IOException - If an IO error occurs during the connect operation
        Since:
        0.2.0
      • connect

        public void connect​(SshConnectionProperties properties,
                            HostKeyVerification hostVerification)
                     throws java.net.UnknownHostException,
                            java.io.IOException

        Connect the client to the server with the specified properties.

        This call attempts to connect to using the connection properties specified. When this method returns the connection has been established, the server's identity been verified and the connection is ready for user authentication. To use this method first create a properties instance and set the required fields.

         SshConnectionProperties properties = new
                                     SshConnectionProperties();
         properties.setHostname("hostname");
         properties.setPort(22);             // Defaults to 22
         // Set the prefered client->server encryption
         ssh.setPrefCSEncryption("blowfish-cbc");
         // Set the prefered server->client encrpytion
         ssh.setPrefSCEncrpyion("3des-cbc");
         ssh.connect(properties);
         

        Host key verification will be performed using the host key verification instance provided:

         // Connect and consult $HOME/.ssh/known_hosts
         ssh.connect("hostname", new ConsoleKnownHostsKeyVerification());
         // Connect and allow any host
         ssh.connect("hostname", new
                         IgnoreHostKeyVerification());
         
        You can provide your own host key verification process by implementing the HostKeyVerification interface.

        Parameters:
        properties - The connection properties
        hostVerification - The host key verification instance to consult for host key validation
        Throws:
        java.net.UnknownHostException - If the host is unknown
        java.io.IOException - If an IO error occurs during the connect operation
        Since:
        0.2.0
      • setKexTimeout

        public void setKexTimeout​(long seconds)
                           throws java.io.IOException

        Sets the timeout value for the key exchange.

        When this time limit is reached the transport protocol will initiate a key re-exchange. The default value is one hour with the minumin timeout being 60 seconds.

        Parameters:
        seconds - The number of seconds beofre key re-exchange
        Throws:
        java.io.IOException - If the timeout value is invalid
        Since:
        0.2.0
      • setKexTransferLimit

        public void setKexTransferLimit​(long kilobytes)
                                 throws java.io.IOException

        Sets the key exchance transfer limit in kilobytes.

        Once this amount of data has been transfered the transport protocol will initiate a key re-exchange. The default value is one gigabyte of data with the mimimun value of 10 kilobytes.

        Parameters:
        kilobytes - The data transfer limit in kilobytes
        Throws:
        java.io.IOException - If the data transfer limit is invalid
      • setSendIgnore

        public void setSendIgnore​(boolean sendIgnore)

        Set's the send ignore flag to send random data packets.

        If this flag is set to true, then the transport protocol will send additional SSH_MSG_IGNORE packets with random data.

        Parameters:
        sendIgnore - true if you want to turn on random packet data, otherwise false
        Since:
        0.2.0
      • setUseDefaultForwarding

        public void setUseDefaultForwarding​(boolean useDefaultForwarding)

        Turn the default forwarding manager on/off.

        If this flag is set to false before connection, the client will not create a port forwarding manager. Use this to provide you own forwarding implementation.

        Parameters:
        useDefaultForwarding - Set to false if you not wish to use the default forwarding manager.
        Since:
        0.2.0
      • disconnect

        public void disconnect()

        Disconnect the client.

        Since:
        0.2.0
      • getOutgoingByteCount

        public long getOutgoingByteCount()

        Returns the number of bytes transmitted to the remote server.

        Returns:
        The number of bytes transmitted
        Since:
        0.2.0
      • getIncomingByteCount

        public long getIncomingByteCount()

        Returns the number of bytes received from the remote server.

        Returns:
        The number of bytes received
        Since:
        0.2.0
      • getActiveChannelCount

        public int getActiveChannelCount()

        Returns the number of active channels for this client.

        This is the total count of sessions, port forwarding, sftp, scp and custom channels currently open.

        Returns:
        The number of active channels
        Since:
        0.2.0
      • getActiveChannels

        public java.util.List getActiveChannels()

        Returns the list of active channels.

        Returns:
        The list of active channels
        Since:
        0.2.0
      • hasActiveSession

        public boolean hasActiveSession​(java.lang.String type)

        Returns true if there is an active session channel of the specified type.

        When a session is created, it is assigned a default type. For instance, when a session is created it as a type of "uninitialized"; however when a shell is started on the session, the type is set to "shell". This also occurs for commands where the type is set to the command which is executed and subsystems where the type is set to the subsystem name. This allows each session to be saved in the active session channel's list and recalled later. It is also possible to set the session channel's type using the setSessionType method of the SessionChannelClient class.

         if(ssh.hasActiveSession("shell")) {
              SessionChannelClient session =
                   ssh.getActiveSession("shell");
         }
         
        Parameters:
        type - The string specifying the channel type
        Returns:
        true if an active session channel exists, otherwise false
        Since:
        0.2.0
      • getActiveSession

        public SessionChannelClient getActiveSession​(java.lang.String type)
                                              throws java.io.IOException

        Returns the active session channel of the given type.

        Parameters:
        type - The type fo session channel
        Returns:
        The session channel instance
        Throws:
        java.io.IOException - If the session type does not exist
        Since:
        0.2.0
      • isActiveChannel

        public boolean isActiveChannel​(Channel channel)
        Determine whether the channel supplied is an active channel
        Parameters:
        channel -
        Returns:
      • openSessionChannel

        public SessionChannelClient openSessionChannel()
                                                throws java.io.IOException

        Open's a session channel on the remote server.

        A session channel may be used to start the user's shell, execute a command or start a subsystem such as SFTP.

        Returns:
        An new session channel
        Throws:
        java.io.IOException - If authentication has not been completed, the server refuses to open the channel or a general IO error occurs
        Since:
        0.2.0
        See Also:
        SessionChannelClient
      • openSessionChannel

        public SessionChannelClient openSessionChannel​(ChannelEventListener eventListener)
                                                throws java.io.IOException

        Open's a session channel on the remote server.

        A session channel may be used to start the user's shell, execute a command or start a subsystem such as SFTP.

        Parameters:
        eventListener - an event listner interface to add to the channel
        Returns:
        Throws:
        java.io.IOException
        SshException
      • openSftpClient

        public SftpClient openSftpClient()
                                  throws java.io.IOException

        Open an SFTP client for file transfer operations.

         SftpClient sftp = ssh.openSftpClient();
         sftp.cd("foo");
         sftp.put("somefile.txt");
         sftp.quit();
         
        Returns:
        Returns an initialized SFTP client
        Throws:
        java.io.IOException - If an IO error occurs during the operation
        Since:
        0.2.0
        See Also:
        SftpClient
      • openSftpClient

        public SftpClient openSftpClient​(ChannelEventListener eventListener)
                                  throws java.io.IOException

        Open an SFTP client for file transfer operations. Adds the supplied event listener to the underlying channel.

        Parameters:
        eventListener -
        Returns:
        Throws:
        java.io.IOException
      • hasActiveSftpClient

        public boolean hasActiveSftpClient()
        Determine if there are existing sftp clients open
        Returns:
      • getActiveSftpClient

        public SftpClient getActiveSftpClient()
                                       throws java.io.IOException
        Get an active sftp client
        Returns:
        Throws:
        java.io.IOException
        SshException
      • openScpClient

        public ScpClient openScpClient()
                                throws java.io.IOException

        Open an SCP client for file transfer operations where SFTP is not supported.

        Sets the local working directory to the user's home directory

         ScpClient scp = ssh.openScpClient();
         scp.put("somefile.txt");
         
        Returns:
        An initialized SCP client
        Throws:
        java.io.IOException - If an IO error occurs during the operation
        Since:
        0.2.0
        See Also:
        ScpClient
      • openScpClient

        public ScpClient openScpClient​(java.io.File cwd)
                                throws java.io.IOException

        Open an SCP client for file transfer operations where SFTP is not supported.

        This method sets a local current working directory.

         ScpClient scp = ssh.openScpClient("foo");
         scp.put("somefile.txt");
         
        Parameters:
        cwd - The local directory as the base for all local files
        Returns:
        An intialized SCP client
        Throws:
        java.io.IOException - If an IO error occurs during the operation
        Since:
        0.2.0
        See Also:
        SftpClient
      • openSftpChannel

        public SftpSubsystemClient openSftpChannel()
                                            throws java.io.IOException

        Open's an Sftp channel.

        Use this sftp channel if you require a lower level api into the SFTP protocol.

        Returns:
        an initialized sftp subsystem instance
        Throws:
        java.io.IOException - if an IO error occurs or the channel cannot be opened
        Since:
        0.2.0
      • openSftpChannel

        public SftpSubsystemClient openSftpChannel​(ChannelEventListener eventListener)
                                            throws java.io.IOException
        Open an SftpSubsystemChannel. For advanced use only
        Parameters:
        eventListener -
        Returns:
        Throws:
        java.io.IOException
        SshException
      • openChannel

        public boolean openChannel​(Channel channel)
                            throws java.io.IOException

        Open's a channel.

        Call this method to open a custom channel. This method is used by all other channel opening methods. For example the openSessionChannel method could be implemented as:

         SessionChannelClient session =
                         new SessionChannelClient();
         if(ssh.openChannel(session)) {
            // Channel is now open
         }
         

        Parameters:
        channel -
        Returns:
        true if the channel was opened, otherwise false
        Throws:
        java.io.IOException - if an IO error occurs
        SshException
        Since:
        0.2.0
      • allowChannelOpen

        public void allowChannelOpen​(java.lang.String channelName,
                                     ChannelFactory cf)
                              throws java.io.IOException

        Instructs the underlying connection protocol to allow channels of the given type to be opened by the server.

        The client does not allow channels to be opened by default. Call this method to allow the server to open channels by providing a ChannelFactory implementation to create instances upon request.

        Parameters:
        channelName - The channel type name
        cf - The factory implementation that will create instances of the channel when a channel open request is recieved.
        Throws:
        java.io.IOException - if an IO error occurs
        Since:
        0.2.0
      • denyChannelOpen

        public void denyChannelOpen​(java.lang.String channelName)
                             throws java.io.IOException

        Stops the specified channel type from being opended.

        Parameters:
        channelName - The channel type name
        Throws:
        java.io.IOException - if an IO error occurs
        Since:
        0.2.1
      • sendGlobalRequest

        public byte[] sendGlobalRequest​(java.lang.String requestName,
                                        boolean wantReply,
                                        byte[] requestData)
                                 throws java.io.IOException

        Send a global request to the server.

        The SSH specification provides a global request mechanism which is used for starting/stopping remote forwarding. This is a general mechanism which can be used for other purposes if the server supports the global requests.

        Parameters:
        requestName - The name of the global request
        wantReply - true if the server should send an explict reply
        requestData - the global request data
        Returns:
        true if the global request succeeded or wantReply==false, otherwise false
        Throws:
        java.io.IOException - if an IO error occurs
        Since:
        0.2.0