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");
....
}
}
activeChannelListener
protected com.sshtools.j2ssh.SshClient.ActiveChannelEventListener activeChannelListener
An channel event listener implemention to maintain the active channel
list.
activeChannels
protected Vector activeChannels
The currently active channels for this SSH Client connection.
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.
authenticationState
protected int authenticationState
The current state of the authentication for the current connection.
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.
eventHandler
protected SshEventAdapter eventHandler
A Transport protocol event handler instance that receives notifications
of transport layer events such as Socket timeouts and disconnection.
forwarding
protected ForwardingClient forwarding
Provides a high level management interface for SSH port forwarding.
socketTimeout
protected int socketTimeout
The timeout in milliseconds for the underlying transport provider
(typically a Socket).
useDefaultForwarding
protected boolean useDefaultForwarding
Flag indicating whether the forwarding instance is created when the
connection is made.
acceptsKey
public boolean acceptsKey(String username,
SshPublicKey key)
throws 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.
username
- The username for authenticationkey
- The public key for which authentication will be attempted
- true if the server will accept the key, otherwise false
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?
}
});
eventHandler
- The event handler instance to receive transport
protocol events
allowChannelOpen
public void allowChannelOpen(String channelName,
ChannelFactory cf)
throws 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.
channelName
- The channel type namecf
- The factory implementation that will create instances of the
channel when a channel open request is recieved.
authenticate
public int authenticate(SshAuthenticationClient auth)
throws 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.
auth
- A configured SshAuthenticationClient instance ready for
authentication
- The authentication result
connect
public void connect(String hostname)
throws 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);
hostname
- The hostname of the server to connect
connect
public void connect(String hostname,
HostKeyVerification hosts)
throws 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.
hostname
- The hostname of the server to connecthosts
- The host key verification instance to consult for host key
validation
connect
public void connect(String hostname,
int port)
throws 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);
hostname
- The hostname of the server to connectport
- The port to connect
connect
public void connect(String hostname,
int port,
HostKeyVerification hosts)
throws 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.
hostname
- The hostname of the server to connectport
- The port to connecthosts
- The host key verification instance to consult for host key
validation
connect
public void connect(SshConnectionProperties properties)
throws 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.
properties
- The connection properties
connect
public void connect(SshConnectionProperties properties,
HostKeyVerification hostVerification)
throws UnknownHostException,
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.
properties
- The connection propertieshostVerification
- The host key verification instance to consult
for host key validation
denyChannelOpen
public void denyChannelOpen(String channelName)
throws IOException
Stops the specified channel type from being opended.
channelName
- The channel type name
disconnect
public void disconnect()
Disconnect the client.
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.
- The number of active channels
getActiveChannels
public List getActiveChannels()
Returns the list of active channels.
- The list of active channels
getActiveSession
public SessionChannelClient getActiveSession(String type)
throws IOException
Returns the active session channel of the given type.
type
- The type fo session channel
- The session channel instance
getActiveSftpClient
public SftpClient getActiveSftpClient()
throws IOException
Get an active sftp client
getAuthenticationBanner
public String getAuthenticationBanner(int timeout)
throws 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.
timeout
- The number of milliseconds to wait for the banner message
before returning
- The server's banner message
getAvailableAuthMethods
public List getAvailableAuthMethods(String username)
throws 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.
username
- The name of the account for which you require the
available authentication methods
- A list of Strings, for example "password", "publickey" &
"keyboard-interactive"
getConnectionProperties
public SshConnectionProperties getConnectionProperties()
Get the connection properties for this connection.
getConnectionState
public TransportProtocolState getConnectionState()
Returns the transport protocol's connection state.
- The transport protocol's state
getForwardingClient
public ForwardingClient getForwardingClient()
Returns the default port forwarding manager.
- This connection's forwarding client
getIncomingByteCount
public long getIncomingByteCount()
Returns the number of bytes received from the remote server.
- The number of bytes received
getOutgoingByteCount
public long getOutgoingByteCount()
Returns the number of bytes transmitted to the remote server.
- The number of bytes transmitted
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.
- The transport protocol's EOL constant
getRemoteEOLString
public 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.
getServerHostKey
public SshPublicKey getServerHostKey()
Returns the server's public key supplied during key exchange.
getServerId
public String getServerId()
Returns the identification string sent by the server during protocol
negotiation. For example "SSH-2.0-OpenSSH_p3.4".
- The server's identification string.
hasActiveSession
public boolean hasActiveSession(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");
}
type
- The string specifying the channel type
- true if an active session channel exists, otherwise false
hasActiveSftpClient
public boolean hasActiveSftpClient()
Determine if there are existing sftp clients open
isActiveChannel
public boolean isActiveChannel(Channel channel)
Determine whether the channel supplied is an active channel
isAuthenticated
public boolean isAuthenticated()
Evaluate whether the client has successfully authenticated.
- true if the client is authenticated, otherwise false
isConnected
public boolean isConnected()
Returns the connection state of the client.
- true if the client is connected, false otherwise
openChannel
public boolean openChannel(Channel channel)
throws 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
}
- true if the channel was opened, otherwise false
openScpClient
public ScpClient openScpClient()
throws 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");
- An initialized SCP client
openScpClient
public ScpClient openScpClient(File cwd)
throws 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");
cwd
- The local directory as the base for all local files
openSessionChannel
public SessionChannelClient openSessionChannel()
throws 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.
openSessionChannel
public SessionChannelClient openSessionChannel(ChannelEventListener eventListener)
throws 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.
eventListener
- an event listner interface to add to the channel
openSftpChannel
public SftpSubsystemClient openSftpChannel()
throws IOException
Open's an Sftp channel.
Use this sftp channel if you require a lower level api into the SFTP
protocol.
- an initialized sftp subsystem instance
openSftpClient
public SftpClient openSftpClient()
throws IOException
Open an SFTP client for file transfer operations.
SftpClient sftp = ssh.openSftpClient();
sftp.cd("foo");
sftp.put("somefile.txt");
sftp.quit();
- Returns an initialized SFTP client
openSftpClient
public SftpClient openSftpClient(ChannelEventListener eventListener)
throws IOException
Open an SFTP client for file transfer operations. Adds the supplied
event listener to the underlying channel.
sendGlobalRequest
public byte[] sendGlobalRequest(String requestName,
boolean wantReply,
byte[] requestData)
throws 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.
requestName
- The name of the global requestwantReply
- true if the server should send an explict replyrequestData
- the global request data
- true if the global request succeeded or wantReply==false,
otherwise false
setKexTimeout
public void setKexTimeout(long seconds)
throws 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.
seconds
- The number of seconds beofre key re-exchange
setKexTransferLimit
public void setKexTransferLimit(long kilobytes)
throws 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.
kilobytes
- The data transfer limit in kilobytes
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.
sendIgnore
- true if you want to turn on random packet data,
otherwise false
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");
milliseconds
- The number of milliseconds without activity before
the timeout event occurs
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.
useDefaultForwarding
- Set to false if you not wish to use the
default forwarding manager.