public class

SSHClient

extends SocketClient
implements Closeable SessionFactory
java.lang.Object
   ↳ net.schmizz.sshj.SocketClient
     ↳ net.schmizz.sshj.SSHClient

Class Overview

Secure SHell client API.

Before connection is established, host key verification needs to be accounted for. This is done by specifying one or more HostKeyVerifier objects. Database of known hostname-key pairs in the OpenSSH "known_hosts" format can be loaded for host key verification.

User authentication can be performed by any of the auth*() method.

startSession() caters to the most typical use case of starting a session channel and executing a remote command, starting a subsystem, etc. If you wish to request X11 forwarding for some session, first register a ConnectListener for x11 channels.

Local and remote port forwarding is possible. There are also utility method for easily creating SCP and SFTP implementations.

A simple example:

 final SSHClient client = new SSHClient();
 client.loadKnownHosts();
 client.connect("hostname");
 try {
     client.authPassword("username", "password");
     final Session session = client.startSession();
     try {
          final Command cmd = session.exec("true");
          cmd.join(1, TimeUnit.SECONDS);
     } finally {
          session.close();
     }
 } finally {
      client.disconnect();
 }
 

Where a password or passphrase is required, if you're extra-paranoid use the char[] based method. The char[] will be blanked out after use.

Summary

Constants
int DEFAULT_PORT Default port for SSH
[Expand]
Inherited Constants
From class net.schmizz.sshj.SocketClient
Fields
protected final UserAuth auth ssh-userauth service
protected final Connection conn ssh-connection service
protected final Logger log Logger
protected final Transport trans Transport layer
[Expand]
Inherited Fields
From class net.schmizz.sshj.SocketClient
Public Constructors
SSHClient()
Default constructor.
SSHClient(Config config)
Constructor that allows specifying a config to be used.
Public Methods
void addHostKeyVerifier(HostKeyVerifier hostKeyVerifier)
Add a HostKeyVerifier which will be invoked for verifying host key during connection establishment and future key exchanges.
void addHostKeyVerifier(String fingerprint)
Add a HostKeyVerifier that will verify any host that's able to claim a host key with the given fingerprint, e.g.
void auth(String username, Iterable<AuthMethod> methods)
Authenticate username using the supplied methods.
void auth(String username, AuthMethod... methods)
Authenticate username using the supplied methods.
void authPassword(String username, char[] password)
Authenticate username using the "password" authentication method and as a fallback basic challenge-response authentication..
void authPassword(String username, PasswordFinder pfinder)
Authenticate username using the "password" authentication method and as a fallback basic challenge-response authentication.
void authPassword(String username, String password)
Authenticate username using the "password" authentication method and as a fallback basic challenge-response authentication.
void authPublickey(String username, String... locations)
Authenticate username using the "publickey" authentication method, with keys from one or more locations in the file system.
void authPublickey(String username, Iterable<KeyProvider> keyProviders)
Authenticate username using the "publickey" authentication method.
void authPublickey(String username, KeyProvider... keyProviders)
Authenticate username using the "publickey" authentication method.
void authPublickey(String username)
Authenticate username using the "publickey" authentication method, with keys from some common locations on the file system.
void close()
Same as disconnect().
void disconnect()
Disconnects from the connected SSH server.
Connection getConnection()
RemotePortForwarder getRemotePortForwarder()
Transport getTransport()
UserAuth getUserAuth()
boolean isAuthenticated()
boolean isConnected()
KeyProvider loadKeys(String location)
Returns a KeyProvider instance created from a location on the file system where an unencrypted private key file (does not require a passphrase) can be found.
KeyProvider loadKeys(String privateKey, String publicKey, PasswordFinder passwordFinder)
Creates a KeyProvider instance from passed strings.
KeyProvider loadKeys(String location, String passphrase)
Convenience method for creating a KeyProvider instance from a location where an encrypted key file is located.
KeyProvider loadKeys(String location, PasswordFinder passwordFinder)
Creates a KeyProvider instance from given location on the file system.
KeyProvider loadKeys(String location, char[] passphrase)
Utility function for createing a KeyProvider instance from given location on the file system.
KeyProvider loadKeys(KeyPair kp)
Creates a KeyProvider from supplied KeyPair.
void loadKnownHosts(File location)
Adds a OpenSSHKnownHosts object created from the specified location as a host key verifier.
void loadKnownHosts()
Attempts loading the user's known_hosts file from the default locations, i.e.
LocalPortForwarder newLocalPortForwarder(LocalPortForwarder.Parameters parameters, ServerSocket serverSocket)
Create a LocalPortForwarder that will listen based on parameters using the bound serverSocket and forward incoming connections to the server; which will further forward them to host:port.
SCPFileTransfer newSCPFileTransfer()
SFTPClient newSFTPClient()
X11Forwarder registerX11Forwarder(ConnectListener listener)
Register a listener for handling forwarded X11 channels.
void rekey()
Does key re-exchange.
Session startSession()
Opens a session channel.
void useCompression()
Adds zlib compression to preferred compression algorithms.
Protected Methods
void doKex()
Do key exchange.
void onConnect()
On connection establishment, also initializes the SSH transport via init(String, int, InputStream, OutputStream) and doKex().
[Expand]
Inherited Methods
From class net.schmizz.sshj.SocketClient
From class java.lang.Object
From interface java.io.Closeable
From interface net.schmizz.sshj.connection.channel.direct.SessionFactory

Constants

public static final int DEFAULT_PORT

Default port for SSH

Constant Value: 22 (0x00000016)

Fields

protected final UserAuth auth

ssh-userauth service

protected final Connection conn

ssh-connection service

protected final Logger log

Logger

protected final Transport trans

Transport layer

Public Constructors

public SSHClient ()

Default constructor. Initializes this object using DefaultConfig.

public SSHClient (Config config)

Constructor that allows specifying a config to be used.

Parameters
config Config instance

Public Methods

public void addHostKeyVerifier (HostKeyVerifier hostKeyVerifier)

Add a HostKeyVerifier which will be invoked for verifying host key during connection establishment and future key exchanges.

Parameters
hostKeyVerifier HostKeyVerifier instance

public void addHostKeyVerifier (String fingerprint)

Add a HostKeyVerifier that will verify any host that's able to claim a host key with the given fingerprint, e.g. "4b:69:6c:72:6f:79:20:77:61:73:20:68:65:72:65:21"

Parameters
fingerprint Expected fingerprint in colon-delimited format (16 octets in hex delimited by a colon)

public void auth (String username, Iterable<AuthMethod> methods)

Authenticate username using the supplied methods.

Parameters
username User to authenticate
methods One or more authentication method
Throws
UserAuthException in case of authentication failure
TransportException if there was a transport-layer error

public void auth (String username, AuthMethod... methods)

Authenticate username using the supplied methods.

Parameters
username User to authenticate
methods One or more authentication method
Throws
UserAuthException in case of authentication failure
TransportException if there was a transport-layer error

public void authPassword (String username, char[] password)

Authenticate username using the "password" authentication method and as a fallback basic challenge-response authentication.. The password array is blanked out after use.

Parameters
username User to authenticate
password The password to use for authentication
Throws
UserAuthException in case of authentication failure
TransportException if there was a transport-layer error

public void authPassword (String username, PasswordFinder pfinder)

Authenticate username using the "password" authentication method and as a fallback basic challenge-response authentication.

Parameters
username User to authenticate
pfinder The PasswordFinder to use for authentication
Throws
UserAuthException in case of authentication failure
TransportException if there was a transport-layer error

public void authPassword (String username, String password)

Authenticate username using the "password" authentication method and as a fallback basic challenge-response authentication.

Parameters
username User to authenticate
password The password to use for authentication
Throws
UserAuthException in case of authentication failure
TransportException if there was a transport-layer error

public void authPublickey (String username, String... locations)

Authenticate username using the "publickey" authentication method, with keys from one or more locations in the file system.

In case multiple locations are specified; authentication is attempted in order as long as the "publickey" authentication method is available. If there is an error loading keys from any of them (e.g. file could not be read, file format not recognized) that key file it is ignored.

This method does not provide a way to specify a passphrase.

Parameters
username User to authenticate
locations One or more locations in the file system containing the private key
Throws
UserAuthException in case of authentication failure
TransportException if there was a transport-layer error

public void authPublickey (String username, Iterable<KeyProvider> keyProviders)

Authenticate username using the "publickey" authentication method.

KeyProvider instances can be created using any of the of the loadKeys() method provided in this class. In case multiple keyProviders are specified; authentication is attempted in order as long as the "publickey" authentication method is available.

Parameters
username User to authenticate
keyProviders One or more KeyProvider instances
Throws
UserAuthException in case of authentication failure
TransportException if there was a transport-layer error

public void authPublickey (String username, KeyProvider... keyProviders)

Authenticate username using the "publickey" authentication method.

KeyProvider instances can be created using any of the loadKeys() method provided in this class. In case multiple keyProviders are specified; authentication is attempted in order as long as the "publickey" authentication method is available.

Parameters
username User to authenticate
keyProviders One or more KeyProvider instances
Throws
UserAuthException in case of authentication failure
TransportException if there was a transport-layer error

public void authPublickey (String username)

Authenticate username using the "publickey" authentication method, with keys from some common locations on the file system. This method relies on ~/.ssh/id_rsa and ~/.ssh/id_dsa.

This method does not provide a way to specify a passphrase.

Parameters
username User to authenticate
Throws
UserAuthException in case of authentication failure
TransportException if there was a transport-layer error

public void close ()

Same as disconnect().

Throws
IOException

public void disconnect ()

Disconnects from the connected SSH server. SSHClient objects are not reusable therefore it is incorrect to attempt connection after this method has been called.

This method should be called from a finally construct after connection is established; so that proper cleanup is done and the thread spawned by the transport layer for dealing with incoming packets is stopped.

Throws
IOException

public Connection getConnection ()

Returns

public RemotePortForwarder getRemotePortForwarder ()

Returns

public Transport getTransport ()

Returns

public UserAuth getUserAuth ()

Returns

public boolean isAuthenticated ()

Returns
  • whether authenticated.

public boolean isConnected ()

Returns
  • whether connected.

public KeyProvider loadKeys (String location)

Returns a KeyProvider instance created from a location on the file system where an unencrypted private key file (does not require a passphrase) can be found. Simply calls loadKeys(String, PasswordFinder) with the PasswordFinder argument as null.

Parameters
location The location for the key file
Returns
  • the key provider ready for use in authentication
Throws
SSHException if there was no suitable key provider available for the file format; typically because BouncyCastle is not in the classpath
IOException if the key file format is not known, if the file could not be read, etc.

public KeyProvider loadKeys (String privateKey, String publicKey, PasswordFinder passwordFinder)

Creates a KeyProvider instance from passed strings. Currently only PKCS8 format private key files are supported (OpenSSH uses this format).

Parameters
privateKey The private key as a string
publicKey The public key as a string if it's not included with the private key
passwordFinder The PasswordFinder that can supply the passphrase for decryption (may be null in case keyfile is not encrypted)
Returns
  • the key provider ready for use in authentication
Throws
SSHException if there was no suitable key provider available for the file format; typically because BouncyCastle is not in the classpath
IOException if the key file format is not known, etc.

public KeyProvider loadKeys (String location, String passphrase)

Convenience method for creating a KeyProvider instance from a location where an encrypted key file is located. Calls loadKeys(String, char[]) with a character array created from the supplied passphrase string.

Parameters
location Location of the key file
passphrase Passphrase as a string
Returns
  • the key provider for use in authentication
Throws
IOException if the key file format is not known, if the file could not be read etc.

public KeyProvider loadKeys (String location, PasswordFinder passwordFinder)

Creates a KeyProvider instance from given location on the file system. Currently only PKCS8 format private key files are supported (OpenSSH uses this format).

Parameters
location The location of the key file
passwordFinder The PasswordFinder that can supply the passphrase for decryption (may be null in case keyfile is not encrypted)
Returns
  • the key provider ready for use in authentication
Throws
SSHException if there was no suitable key provider available for the file format; typically because BouncyCastle is not in the classpath
IOException if the key file format is not known, if the file could not be read, etc.

public KeyProvider loadKeys (String location, char[] passphrase)

Utility function for createing a KeyProvider instance from given location on the file system. Creates a one-off PasswordFinder using createOneOff(char[]), and calls loadKeys(String, PasswordFinder).

Parameters
location Location of the key file
passphrase Passphrase as a char-array
Returns
  • the key provider ready for use in authentication
Throws
SSHException if there was no suitable key provider available for the file format; typically because BouncyCastle is not in the classpath
IOException if the key file format is not known, if the file could not be read, etc.

public KeyProvider loadKeys (KeyPair kp)

Creates a KeyProvider from supplied KeyPair.

Parameters
kp The key pair
Returns
  • the key provider ready for use in authentication

public void loadKnownHosts (File location)

Adds a OpenSSHKnownHosts object created from the specified location as a host key verifier.

Parameters
location Location for known_hosts file
Throws
IOException if there is an error loading from any of these locations

public void loadKnownHosts ()

Attempts loading the user's known_hosts file from the default locations, i.e. ~/.ssh/known_hosts and ~/.ssh/known_hosts2 on most platforms. Adds the resulting OpenSSHKnownHosts object as a host key verifier.

For finer control over which file is used, see loadKnownHosts(File).

Throws
IOException if there is an error loading from both locations

public LocalPortForwarder newLocalPortForwarder (LocalPortForwarder.Parameters parameters, ServerSocket serverSocket)

Create a LocalPortForwarder that will listen based on parameters using the bound serverSocket and forward incoming connections to the server; which will further forward them to host:port.

The returned forwarder's listen() method should be called to actually start listening, this method just creates an instance.

Parameters
parameters Parameters for the forwarding setup
serverSocket Bound server socket
Returns

public SCPFileTransfer newSCPFileTransfer ()

Returns

public SFTPClient newSFTPClient ()

Returns
Throws
IOException if there is an error starting the sftp subsystem

public X11Forwarder registerX11Forwarder (ConnectListener listener)

Register a listener for handling forwarded X11 channels. Without having done this, an incoming X11 forwarding will be summarily rejected.

It should be clarified that multiple listeners for X11 forwarding over a single SSH connection are not supported (and don't make much sense). So a subsequent call to this method is only going to replace the registered listener.

Parameters
listener The ConnectListener that should be delegated the responsibility of handling forwarded X11Forwarder.X11Channel 's
Returns

public void rekey ()

Does key re-exchange.

Throws
TransportException if an error occurs during key exchange

public Session startSession ()

Opens a session channel. The returned Session instance allows executing a remote command, starting a subsystem, or starting a shell.

Returns
  • the opened session channel

public void useCompression ()

Adds zlib compression to preferred compression algorithms. There is no guarantee that it will be successfully negotiatied.

If the client is already connected renegotiation is done; otherwise this method simply returns (and compression will be negotiated during connection establishment).

Throws
ClassNotFoundException if JZlib is not in classpath
TransportException if an error occurs during renegotiation

Protected Methods

protected void doKex ()

Do key exchange.

Throws
TransportException if error during kex

protected void onConnect ()

On connection establishment, also initializes the SSH transport via init(String, int, InputStream, OutputStream) and doKex().

Throws
IOException