Package net.schmizz.sshj
Class SSHClient
java.lang.Object
net.schmizz.sshj.SocketClient
net.schmizz.sshj.SSHClient
- All Implemented Interfaces:
RemoteAddressProvider
,Closeable
,AutoCloseable
,SessionFactory
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.-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected final UserAuth
ssh-userauth
serviceprotected final Connection
ssh-connection
servicestatic final int
Default port for SSHprivate final List
<LocalPortForwarder> protected final org.slf4j.Logger
protected final LoggerFactory
Loggerprotected Charset
character set of the remote machineprotected final Transport
Transport layer -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoid
addAlgorithmsVerifier
(AlgorithmsVerifier verifier) Add aAlgorithmsVerifier
which will be invoked for verifying negotiated algorithms.void
addHostKeyVerifier
(String fingerprint) Add aHostKeyVerifier
that will verify any host that's able to claim a host key with the givenfingerprint
.void
addHostKeyVerifier
(HostKeyVerifier verifier) Add aHostKeyVerifier
which will be invoked for verifying host key during connection establishment and future key exchanges.void
auth
(String username, Iterable<AuthMethod> methods) Authenticateusername
using the suppliedmethods
.void
auth
(String username, AuthMethod... methods) Authenticateusername
using the suppliedmethods
.void
authGssApiWithMic
(String username, LoginContext context, Oid supportedOid, Oid... supportedOids) Authenticateusername
using the"gssapi-with-mic"
authentication method, given a login context for the peer GSS machine and a list of supported OIDs.void
authPassword
(String username, char[] password) Authenticateusername
using the"password"
authentication method and as a fallback basic challenge-response authentication..void
authPassword
(String username, String password) Authenticateusername
using the"password"
authentication method and as a fallback basic challenge-response authentication.void
authPassword
(String username, PasswordFinder pfinder) Authenticateusername
using the"password"
authentication method and as a fallback basic challenge-response authentication.void
authPassword
(String username, PasswordFinder pfinder, PasswordUpdateProvider newPasswordProvider) Authenticateusername
using the"password"
authentication method and as a fallback basic challenge-response authentication.void
authPublickey
(String username) Authenticateusername
using the"publickey"
authentication method, with keys from some common locations on the file system.void
authPublickey
(String username, Iterable<KeyProvider> keyProviders) Authenticateusername
using the"publickey"
authentication method.void
authPublickey
(String username, String... locations) Authenticateusername
using the"publickey"
authentication method, with keys from one or morelocations
in the file system.void
authPublickey
(String username, KeyProvider... keyProviders) Authenticateusername
using the"publickey"
authentication method.private void
private void
void
close()
Same asdisconnect()
.void
Disconnects from the connected SSH server.protected void
doKex()
Do key exchange.Returns the character set used to communicate with the remote machine for certain strings (like paths).Get Remote Socket Address from Transportboolean
boolean
Returns aKeyProvider
instance created from a location on the file system where an unencrypted private key file (does not require a passphrase) can be found.Utility function for creating aKeyProvider
instance from given location on the file system.Convenience method for creating aKeyProvider
instance from alocation
where an encrypted key file is located.loadKeys
(String privateKey, String publicKey, PasswordFinder passwordFinder) Creates aKeyProvider
instance from passed strings.loadKeys
(String location, PasswordFinder passwordFinder) Creates aKeyProvider
instance from given location on the file system.Creates aKeyProvider
from suppliedKeyPair
.void
Attempts loading the user'sknown_hosts
file from the default locations, i.e.void
loadKnownHosts
(File location) Adds aOpenSSHKnownHosts
object created from the specified location as a host key verifier.newDirectConnection
(String hostname, int port) Create aDirectConnection
channel that connects to a remote address from the server.newLocalPortForwarder
(Parameters parameters, ServerSocket serverSocket) Create aLocalPortForwarder
that will listen based onparameters
using the boundserverSocket
and forward incoming connections to the server; which will further forward them tohost:port
.Stateful FTP client is required in order to connect to Serv-U FTP servers.protected void
On connection establishment, also initializes the SSH transport viaTransport.init(java.lang.String, int, java.io.InputStream, java.io.OutputStream)
anddoKex()
.registerX11Forwarder
(ConnectListener listener) Register alistener
for handling forwarded X11 channels.void
rekey()
Does key re-exchange.void
setRemoteCharset
(Charset remoteCharset) Sets the character set used to communicate with the remote machine for certain strings (like paths)Opens asession
channel.void
Addszlib
compression to preferred compression algorithms.Methods inherited from class net.schmizz.sshj.SocketClient
connect, connect, connect, connect, connect, connect, connectVia, connectVia, getConnectTimeout, getInputStream, getLocalAddress, getLocalPort, getOutputStream, getRemoteAddress, getRemoteHostname, getRemotePort, getSocket, getSocketFactory, getTimeout, makeInetSocketAddress, setConnectTimeout, setSocketFactory, setTimeout
-
Field Details
-
DEFAULT_PORT
public static final int DEFAULT_PORTDefault port for SSH- See Also:
-
loggerFactory
Logger -
log
protected final org.slf4j.Logger log -
trans
Transport layer -
auth
ssh-userauth
service -
conn
ssh-connection
service -
forwarders
-
remoteCharset
character set of the remote machine
-
-
Constructor Details
-
SSHClient
public SSHClient()Default constructor. Initializes this object usingDefaultConfig
. -
SSHClient
Constructor that allows specifying aconfig
to be used.- Parameters:
config
-Config
instance
-
-
Method Details
-
addHostKeyVerifier
Add aHostKeyVerifier
which will be invoked for verifying host key during connection establishment and future key exchanges.- Parameters:
verifier
-HostKeyVerifier
instance
-
addAlgorithmsVerifier
Add aAlgorithmsVerifier
which will be invoked for verifying negotiated algorithms.- Parameters:
verifier
-AlgorithmsVerifier
instance
-
addHostKeyVerifier
Add aHostKeyVerifier
that will verify any host that's able to claim a host key with the givenfingerprint
. The fingerprint can be specified in either an MD5 colon-delimited format (16 hexadecimal octets, delimited by a colon), or in a Base64 encoded format for SHA-1 or SHA-256 fingerprints. Valid examples are:- "SHA1:2Fo8c/96zv32xc8GZWbOGYOlRak="
- "SHA256:oQGbQTujGeNIgh0ONthcEpA/BHxtt3rcYY+NxXTxQjs="
- "MD5:d3:5e:40:72:db:08:f1:6d:0c:d7:6d:35:0d:ba:7c:32"
- "d3:5e:40:72:db:08:f1:6d:0c:d7:6d:35:0d:ba:7c:32"
- Parameters:
fingerprint
- expected fingerprint in colon-delimited format (16 octets in hex delimited by a colon)- See Also:
-
auth
public void auth(String username, AuthMethod... methods) throws UserAuthException, TransportException Authenticateusername
using the suppliedmethods
.- Parameters:
username
- user to authenticatemethods
- one or more authentication method- Throws:
UserAuthException
- in case of authentication failureTransportException
- if there was a transport-layer error
-
auth
public void auth(String username, Iterable<AuthMethod> methods) throws UserAuthException, TransportException Authenticateusername
using the suppliedmethods
.- Parameters:
username
- user to authenticatemethods
- one or more authentication method- Throws:
UserAuthException
- in case of authentication failureTransportException
- if there was a transport-layer error
-
authPassword
public void authPassword(String username, String password) throws UserAuthException, TransportException Authenticateusername
using the"password"
authentication method and as a fallback basic challenge-response authentication.- Parameters:
username
- user to authenticatepassword
- the password to use for authentication- Throws:
UserAuthException
- in case of authentication failureTransportException
- if there was a transport-layer error
-
authPassword
public void authPassword(String username, char[] password) throws UserAuthException, TransportException Authenticateusername
using the"password"
authentication method and as a fallback basic challenge-response authentication.. Thepassword
array is blanked out after use.- Parameters:
username
- user to authenticatepassword
- the password to use for authentication- Throws:
UserAuthException
- in case of authentication failureTransportException
- if there was a transport-layer error
-
authPassword
public void authPassword(String username, PasswordFinder pfinder) throws UserAuthException, TransportException Authenticateusername
using the"password"
authentication method and as a fallback basic challenge-response authentication.- Parameters:
username
- user to authenticatepfinder
- thePasswordFinder
to use for authentication- Throws:
UserAuthException
- in case of authentication failureTransportException
- if there was a transport-layer error
-
authPassword
public void authPassword(String username, PasswordFinder pfinder, PasswordUpdateProvider newPasswordProvider) throws UserAuthException, TransportException Authenticateusername
using the"password"
authentication method and as a fallback basic challenge-response authentication.- Parameters:
username
- user to authenticatepfinder
- thePasswordFinder
to use for authenticationnewPasswordProvider
- thePasswordUpdateProvider
to use when a new password is being requested from the user.- Throws:
UserAuthException
- in case of authentication failureTransportException
- if there was a transport-layer error
-
authPublickey
Authenticateusername
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 failureTransportException
- if there was a transport-layer error
-
authPublickey
public void authPublickey(String username, Iterable<KeyProvider> keyProviders) throws UserAuthException, TransportException Authenticateusername
using the"publickey"
authentication method.KeyProvider
instances can be created using any of the of theloadKeys()
method provided in this class. In case multiplekeyProviders
are specified; authentication is attempted in order as long as the"publickey"
authentication method is available.- Parameters:
username
- user to authenticatekeyProviders
- one or moreKeyProvider
instances- Throws:
UserAuthException
- in case of authentication failureTransportException
- if there was a transport-layer error
-
authPublickey
public void authPublickey(String username, KeyProvider... keyProviders) throws UserAuthException, TransportException Authenticateusername
using the"publickey"
authentication method.KeyProvider
instances can be created using any of theloadKeys()
method provided in this class. In case multiplekeyProviders
are specified; authentication is attempted in order as long as the"publickey"
authentication method is available.- Parameters:
username
- user to authenticatekeyProviders
- one or moreKeyProvider
instances- Throws:
UserAuthException
- in case of authentication failureTransportException
- if there was a transport-layer error
-
authPublickey
public void authPublickey(String username, String... locations) throws UserAuthException, TransportException Authenticateusername
using the"publickey"
authentication method, with keys from one or morelocations
in the file system. In case multiplelocations
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 authenticatelocations
- one or more locations in the file system containing the private key- Throws:
UserAuthException
- in case of authentication failureTransportException
- if there was a transport-layer error
-
authGssApiWithMic
public void authGssApiWithMic(String username, LoginContext context, Oid supportedOid, Oid... supportedOids) throws UserAuthException, TransportException Authenticateusername
using the"gssapi-with-mic"
authentication method, given a login context for the peer GSS machine and a list of supported OIDs. Supported OIDs should be ordered by preference as the SSH server will choose the first OID that it also supports. At least one OID is required- Parameters:
username
- user to authenticatecontext
-LoginContext
for the peer GSS machinesupportedOid
- first supported OIDsupportedOids
- other supported OIDs- Throws:
UserAuthException
- in case of authentication failureTransportException
- if there was a transport-layer error
-
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 afinally
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.- Overrides:
disconnect
in classSocketClient
- Throws:
IOException
-
getConnection
- Returns:
- the associated
Connection
instance.
-
getRemoteSocketAddress
Get Remote Socket Address from Transport- Specified by:
getRemoteSocketAddress
in interfaceRemoteAddressProvider
- Returns:
- Remote Socket Address or null when not connected
-
getRemoteCharset
Returns the character set used to communicate with the remote machine for certain strings (like paths).- Returns:
- remote character set
-
getRemotePortForwarder
- Returns:
- a
RemotePortForwarder
that allows requesting remote forwarding over this connection.
-
getTransport
- Returns:
- the associated
Transport
instance.
-
getUserAuth
- Returns:
- the associated
UserAuth
instance. This allows access to information like theauthentication banner
, whether authentication was at leastpartially successful
.
-
isAuthenticated
public boolean isAuthenticated()- Returns:
- whether authenticated.
-
isConnected
public boolean isConnected()- Overrides:
isConnected
in classSocketClient
- Returns:
- whether connected.
-
loadKeys
Creates aKeyProvider
from suppliedKeyPair
.- Parameters:
kp
- the key pair- Returns:
- the key provider ready for use in authentication
-
loadKeys
Returns aKeyProvider
instance created from a location on the file system where an unencrypted private key file (does not require a passphrase) can be found. Simply callsloadKeys(String, PasswordFinder)
with thePasswordFinder
argument asnull
.- 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 classpathIOException
- if the key file format is not known, if the file could not be read, etc.
-
loadKeys
Utility function for creating aKeyProvider
instance from given location on the file system. Creates a one-offPasswordFinder
usingPasswordUtils.createOneOff(char[])
, and callsloadKeys(String, PasswordFinder)
.- Parameters:
location
- location of the key filepassphrase
- 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 classpathIOException
- if the key file format is not known, if the file could not be read, etc.
-
loadKeys
Creates aKeyProvider
instance from given location on the file system. Currently the following private key files are supported:- PKCS8 (OpenSSH uses this format)
- PEM-encoded PKCS1
- Putty keyfile
- openssh-key-v1 (New OpenSSH keyfile format)
- Parameters:
location
- the location of the key filepasswordFinder
- thePasswordFinder
that can supply the passphrase for decryption (may benull
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 classpathIOException
- if the key file format is not known, if the file could not be read, etc.
-
loadKeys
Convenience method for creating aKeyProvider
instance from alocation
where an encrypted key file is located. CallsloadKeys(String, char[])
with a character array created from the suppliedpassphrase
string.- Parameters:
location
- location of the key filepassphrase
- 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.
-
loadKeys
public KeyProvider loadKeys(String privateKey, String publicKey, PasswordFinder passwordFinder) throws IOException Creates aKeyProvider
instance from passed strings. Currently only PKCS8 format private key files are supported (OpenSSH uses this format).- Parameters:
privateKey
- the private key as a stringpublicKey
- the public key as a string if it's not included with the private keypasswordFinder
- thePasswordFinder
that can supply the passphrase for decryption (may benull
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 classpathIOException
- if the key file format is not known, etc.
-
loadKnownHosts
Attempts loading the user'sknown_hosts
file from the default locations, i.e.~/.ssh/known_hosts
and~/.ssh/known_hosts2
on most platforms. Adds the resultingOpenSSHKnownHosts
object as a host key verifier. For finer control over which file is used, seeloadKnownHosts(File)
.- Throws:
IOException
- if there is an error loading from both locations
-
loadKnownHosts
Adds aOpenSSHKnownHosts
object created from the specified location as a host key verifier.- Parameters:
location
- location forknown_hosts
file- Throws:
IOException
- if there is an error loading from any of these locations
-
newLocalPortForwarder
Create aLocalPortForwarder
that will listen based onparameters
using the boundserverSocket
and forward incoming connections to the server; which will further forward them tohost:port
. The returned forwarder'slisten()
method should be called to actually start listening, this method just creates an instance.- Parameters:
parameters
- parameters for the forwarding setupserverSocket
- bound server socket- Returns:
- a
LocalPortForwarder
-
newDirectConnection
Create aDirectConnection
channel that connects to a remote address from the server. This can be used to open a tunnel to, for example, an HTTP server that is only accessible from the SSH server, or opening an SSH connection via a 'jump' server.- Parameters:
hostname
- name of the host to connect to from the server.port
- remote port number.- Throws:
IOException
-
registerX11Forwarder
Register alistener
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 registeredlistener
.- Parameters:
listener
- theConnectListener
that should be delegated the responsibility of handling forwardedX11Forwarder.X11Channel
's- Returns:
- an
X11Forwarder
that allows tostop acting
on X11 requests from server
-
newSCPFileTransfer
- Returns:
- Instantiated
SCPFileTransfer
implementation.
-
newSFTPClient
- Returns:
- Instantiated
SFTPClient
implementation. - Throws:
IOException
- if there is an error starting thesftp
subsystem- See Also:
-
newStatefulSFTPClient
Stateful FTP client is required in order to connect to Serv-U FTP servers.- Returns:
- Instantiated
SFTPClient
implementation. - Throws:
IOException
- if there is an error starting thesftp
subsystem
-
rekey
Does key re-exchange.- Throws:
TransportException
- if an error occurs during key exchange
-
setRemoteCharset
Sets the character set used to communicate with the remote machine for certain strings (like paths)- Parameters:
remoteCharset
- remote character set ornull
for default
-
startSession
Description copied from interface:SessionFactory
Opens asession
channel. The returnedSession
instance allowsexecuting a remote command
,starting a subsystem
, orstarting a shell
.- Specified by:
startSession
in interfaceSessionFactory
- Returns:
- the opened
session
channel - Throws:
ConnectionException
TransportException
- See Also:
-
useCompression
Addszlib
compression to preferred compression algorithms. There is no guarantee that it will be successfully negotiated. If the client is already connected renegotiation is done; otherwise this method simply returns (and compression will be negotiated during connection establishment).- Throws:
ClassNotFoundException
- ifJZlib
is not in classpathTransportException
- if an error occurs during renegotiation
-
onConnect
On connection establishment, also initializes the SSH transport viaTransport.init(java.lang.String, int, java.io.InputStream, java.io.OutputStream)
anddoKex()
.- Overrides:
onConnect
in classSocketClient
- Throws:
IOException
-
doKex
Do key exchange.- Throws:
TransportException
- if error during kex
-
close
Same asdisconnect()
.- Specified by:
close
in interfaceAutoCloseable
- Specified by:
close
in interfaceCloseable
- Throws:
IOException
-
checkConnected
private void checkConnected() -
checkAuthenticated
private void checkAuthenticated()
-