|
|||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Objectcom.sshtools.j2ssh.SshClient
public class SshClient
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:
Once this code has executed and returned the connection is ready for authentication:// Create a instance and connect SshClient ssh = new SshClient(); ssh.connect("hostname");
Once authenticated the user's shell can be started:PasswordAuthenticationClient pwd = new PasswordAuthenticationClient(); pwd.setUsername("foo"); pwd.setPassword("xxxxx"); // Authenticate the user int result = ssh.authenticate(pwd); if(result==AuthenticationProtocolState.COMPLETED) { // Authentication complete }
// 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"); .... } }
Field Summary | |
---|---|
protected com.sshtools.j2ssh.SshClient.ActiveChannelEventListener |
activeChannelListener
An channel event listener implemention to maintain the active channel list. |
protected java.util.Vector |
activeChannels
The currently active channels for this SSH Client connection. |
protected AuthenticationProtocolClient |
authentication
The SSH Authentication protocol implementation for this SSH client. |
protected int |
authenticationState
The current state of the authentication for the current connection. |
protected ConnectionProtocol |
connection
The SSH Connection protocol implementation for this SSH client. |
protected SshEventAdapter |
eventHandler
A Transport protocol event handler instance that receives notifications of transport layer events such as Socket timeouts and disconnection. |
protected ForwardingClient |
forwarding
Provides a high level management interface for SSH port forwarding. |
protected int |
socketTimeout
The timeout in milliseconds for the underlying transport provider (typically a Socket). |
protected TransportProtocolClient |
transport
The SSH Transport protocol implementation for this SSH Client. |
protected boolean |
useDefaultForwarding
Flag indicating whether the forwarding instance is created when the connection is made. |
Constructor Summary | |
---|---|
SshClient()
Contructs an unitilialized SshClient ready for connecting. |
Method Summary | |
---|---|
boolean |
acceptsKey(java.lang.String username,
SshPublicKey key)
Determine whether a private/public key pair will be accepted for public key authentication. |
void |
addEventHandler(SshEventAdapter eventHandler)
Set the event handler for the underlying transport protocol. |
void |
allowChannelOpen(java.lang.String channelName,
ChannelFactory cf)
Instructs the underlying connection protocol to allow channels of the given type to be opened by the server. |
int |
authenticate(SshAuthenticationClient auth)
Authenticate the user on the remote host. |
void |
connect(SshConnectionProperties properties)
Connect the client to the server with the specified properties. |
void |
connect(SshConnectionProperties properties,
HostKeyVerification hostVerification)
Connect the client to the server with the specified properties. |
void |
connect(java.lang.String hostname)
Connect the client to the server using default connection properties. |
void |
connect(java.lang.String hostname,
HostKeyVerification hosts)
Connect the client to the server using the default connection properties. |
void |
connect(java.lang.String hostname,
int port)
Connect the client to the server on a specified port with default connection properties. |
void |
connect(java.lang.String hostname,
int port,
HostKeyVerification hosts)
Connect the client to the server on a specified port with default connection properties. |
void |
denyChannelOpen(java.lang.String channelName)
Stops the specified channel type from being opended. |
void |
disconnect()
Disconnect the client. |
int |
getActiveChannelCount()
Returns the number of active channels for this client. |
java.util.List |
getActiveChannels()
Returns the list of active channels. |
SessionChannelClient |
getActiveSession(java.lang.String type)
Returns the active session channel of the given type. |
SftpClient |
getActiveSftpClient()
Get an active sftp client |
java.lang.String |
getAuthenticationBanner(int timeout)
Returns the server's authentication banner. |
java.util.List |
getAvailableAuthMethods(java.lang.String username)
Returns the list of available authentication methods for a given user. |
SshConnectionProperties |
getConnectionProperties()
Get the connection properties for this connection. |
TransportProtocolState |
getConnectionState()
Returns the transport protocol's connection state. |
ForwardingClient |
getForwardingClient()
Returns the default port forwarding manager. |
long |
getIncomingByteCount()
Returns the number of bytes received from the remote server. |
long |
getOutgoingByteCount()
Returns the number of bytes transmitted to the remote server. |
int |
getRemoteEOL()
Return's a rough guess at the server's EOL setting. |
java.lang.String |
getRemoteEOLString()
Return's a rough guess at the server's EOL setting. |
SshPublicKey |
getServerHostKey()
Returns the server's public key supplied during key exchange. |
java.lang.String |
getServerId()
Returns the identification string sent by the server during protocol negotiation. |
boolean |
hasActiveSession(java.lang.String type)
Returns true if there is an active session channel of the specified type. |
boolean |
hasActiveSftpClient()
Determine if there are existing sftp clients open |
boolean |
isActiveChannel(Channel channel)
Determine whether the channel supplied is an active channel |
boolean |
isAuthenticated()
Evaluate whether the client has successfully authenticated. |
boolean |
isConnected()
Returns the connection state of the client. |
boolean |
openChannel(Channel channel)
Open's a channel. |
ScpClient |
openScpClient()
Open an SCP client for file transfer operations where SFTP is not supported. |
ScpClient |
openScpClient(java.io.File cwd)
Open an SCP client for file transfer operations where SFTP is not supported. |
SessionChannelClient |
openSessionChannel()
Open's a session channel on the remote server. |
SessionChannelClient |
openSessionChannel(ChannelEventListener eventListener)
Open's a session channel on the remote server. |
SftpSubsystemClient |
openSftpChannel()
Open's an Sftp channel. |
SftpSubsystemClient |
openSftpChannel(ChannelEventListener eventListener)
Open an SftpSubsystemChannel. |
SftpClient |
openSftpClient()
Open an SFTP client for file transfer operations. |
SftpClient |
openSftpClient(ChannelEventListener eventListener)
Open an SFTP client for file transfer operations. |
byte[] |
sendGlobalRequest(java.lang.String requestName,
boolean wantReply,
byte[] requestData)
Send a global request to the server. |
void |
setKexTimeout(long seconds)
Sets the timeout value for the key exchange. |
void |
setKexTransferLimit(long kilobytes)
Sets the key exchance transfer limit in kilobytes. |
void |
setSendIgnore(boolean sendIgnore)
Set's the send ignore flag to send random data packets. |
void |
setSocketTimeout(int milliseconds)
Set's the socket timeout (in milliseconds) for the underlying transport provider. |
void |
setUseDefaultForwarding(boolean useDefaultForwarding)
Turn the default forwarding manager on/off. |
Methods inherited from class java.lang.Object |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Field Detail |
---|
protected AuthenticationProtocolClient authentication
protected ConnectionProtocol connection
protected ForwardingClient forwarding
protected TransportProtocolClient transport
protected int authenticationState
protected int socketTimeout
protected SshEventAdapter eventHandler
protected java.util.Vector activeChannels
protected com.sshtools.j2ssh.SshClient.ActiveChannelEventListener activeChannelListener
protected boolean useDefaultForwarding
Constructor Detail |
---|
public SshClient()
Contructs an unitilialized SshClient ready for connecting.
Method Detail |
---|
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.
timeout
- The number of milliseconds to wait for the banner message
before returning
java.io.IOException
- If an IO error occurs reading the messagepublic 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.
username
- The name of the account for which you require the
available authentication methods
java.io.IOException
- If an IO error occurs during the operationpublic boolean isConnected()
Returns the connection state of the client.
public boolean isAuthenticated()
Evaluate whether the client has successfully authenticated.
public java.lang.String getServerId()
Returns the identification string sent by the server during protocol negotiation. For example "SSH-2.0-OpenSSH_p3.4".
public SshPublicKey getServerHostKey()
Returns the server's public key supplied during key exchange.
public TransportProtocolState getConnectionState()
Returns the transport protocol's connection state.
public ForwardingClient getForwardingClient()
Returns the default port forwarding manager.
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.
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 eventsTransportProtocolEventHandler
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 occurspublic 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.
public SshConnectionProperties getConnectionProperties()
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.
auth
- A configured SshAuthenticationClient instance ready for
authentication
java.io.IOException
- If an IO error occurs during authenticationpublic 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.
username
- The username for authenticationkey
- The public key for which authentication will be attempted
java.io.IOException
- If an IO error occurs during the operation
SshException
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);
hostname
- The hostname of the server to connect
java.io.IOException
- If an IO error occurs during the connect
operationconnect(com.sshtools.j2ssh.configuration.SshConnectionProperties)
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.
hostname
- The hostname of the server to connecthosts
- The host key verification instance to consult for host key
validation
java.io.IOException
- If an IO error occurs during the connect
operationconnect(com.sshtools.j2ssh.configuration.SshConnectionProperties,
com.sshtools.j2ssh.transport.HostKeyVerification)
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);
hostname
- The hostname of the server to connectport
- The port to connect
java.io.IOException
- If an IO error occurs during the connect
operationconnect(com.sshtools.j2ssh.configuration.SshConnectionProperties)
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.
hostname
- The hostname of the server to connectport
- The port to connecthosts
- The host key verification instance to consult for host key
validation
java.io.IOException
- If an IO error occurs during the connect
operationconnect(com.sshtools.j2ssh.configuration.SshConnectionProperties,
com.sshtools.j2ssh.transport.HostKeyVerification)
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.
properties
- The connection properties
java.io.IOException
- If an IO error occurs during the connect
operationpublic 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:
You can provide your own host key verification process by implementing the// Connect and consult $HOME/.ssh/known_hosts ssh.connect("hostname", new ConsoleKnownHostsKeyVerification()); // Connect and allow any host ssh.connect("hostname", new IgnoreHostKeyVerification());
HostKeyVerification
interface.
properties
- The connection propertieshostVerification
- The host key verification instance to consult
for host key validation
java.net.UnknownHostException
- If the host is unknown
java.io.IOException
- If an IO error occurs during the connect
operationpublic 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.
seconds
- The number of seconds beofre key re-exchange
java.io.IOException
- If the timeout value is invalidpublic 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.
kilobytes
- The data transfer limit in kilobytes
java.io.IOException
- If the data transfer limit is invalidpublic 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 falsepublic 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.public void disconnect()
Disconnect the client.
public long getOutgoingByteCount()
Returns the number of bytes transmitted to the remote server.
public long getIncomingByteCount()
Returns the number of bytes received from the remote server.
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.
public java.util.List getActiveChannels()
Returns the list of active channels.
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"); }
type
- The string specifying the channel type
public SessionChannelClient getActiveSession(java.lang.String type) throws java.io.IOException
Returns the active session channel of the given type.
type
- The type fo session channel
java.io.IOException
- If the session type does not existpublic boolean isActiveChannel(Channel channel)
channel
-
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.
java.io.IOException
- If authentication has not been completed, the
server refuses to open the channel or a general IO error
occursSessionChannelClient
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.
eventListener
- an event listner interface to add to the channel
java.io.IOException
SshException
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();
java.io.IOException
- If an IO error occurs during the operationSftpClient
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.
eventListener
-
java.io.IOException
public boolean hasActiveSftpClient()
public SftpClient getActiveSftpClient() throws java.io.IOException
java.io.IOException
SshException
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");
java.io.IOException
- If an IO error occurs during the operationScpClient
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");
cwd
- The local directory as the base for all local files
java.io.IOException
- If an IO error occurs during the operationSftpClient
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.
java.io.IOException
- if an IO error occurs or the channel cannot be
openedpublic SftpSubsystemClient openSftpChannel(ChannelEventListener eventListener) throws java.io.IOException
eventListener
-
java.io.IOException
SshException
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 }
channel
-
java.io.IOException
- if an IO error occurs
SshException
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.
channelName
- The channel type namecf
- The factory implementation that will create instances of the
channel when a channel open request is recieved.
java.io.IOException
- if an IO error occurspublic void denyChannelOpen(java.lang.String channelName) throws java.io.IOException
Stops the specified channel type from being opended.
channelName
- The channel type name
java.io.IOException
- if an IO error occurspublic 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.
requestName
- The name of the global requestwantReply
- true if the server should send an explict replyrequestData
- the global request data
java.io.IOException
- if an IO error occurs
|
|||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |