Package net.schmizz.sshj
Class SSHClient
- java.lang.Object
-
- net.schmizz.sshj.SocketClient
-
- net.schmizz.sshj.SSHClient
-
- All Implemented Interfaces:
RemoteAddressProvider,java.io.Closeable,java.lang.AutoCloseable,SessionFactory
public class SSHClient extends SocketClient implements java.io.Closeable, SessionFactory
Secure SHell client API. Before connection is established, host key verification needs to be accounted for. This is done byspecifyingone or moreHostKeyVerifierobjects. Database of known hostname-key pairs in the OpenSSH"known_hosts"format can beloadedfor host key verification. User authentication can be performed by any of theauth*()method.startSession()caters to the most typical use case of starting asessionchannel and executing a remote command, starting a subsystem, etc. If you wish to request X11 forwarding for some session, firstregisteraConnectListenerforx11channels.Localandremoteport forwarding is possible. There are also utility method for easily creatingSCPandSFTPimplementations. 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 thechar[]based method. Thechar[]will be blanked out after use.
-
-
Field Summary
Fields Modifier and Type Field Description protected UserAuthauthssh-userauthserviceprotected Connectionconnssh-connectionservicestatic intDEFAULT_PORTDefault port for SSHprotected org.slf4j.Loggerlogprotected LoggerFactoryloggerFactoryLoggerprotected java.nio.charset.CharsetremoteCharsetcharacter set of the remote machineprotected TransporttransTransport layer
-
Method Summary
Modifier and Type Method Description voidaddAlgorithmsVerifier(AlgorithmsVerifier verifier)Add aAlgorithmsVerifierwhich will be invoked for verifying negotiated algorithms.voidaddHostKeyVerifier(java.lang.String fingerprint)Add aHostKeyVerifierthat will verify any host that's able to claim a host key with the givenfingerprint.voidaddHostKeyVerifier(HostKeyVerifier verifier)Add aHostKeyVerifierwhich will be invoked for verifying host key during connection establishment and future key exchanges.voidauth(java.lang.String username, java.lang.Iterable<AuthMethod> methods)Authenticateusernameusing the suppliedmethods.voidauth(java.lang.String username, AuthMethod... methods)Authenticateusernameusing the suppliedmethods.voidauthGssApiWithMic(java.lang.String username, javax.security.auth.login.LoginContext context, org.ietf.jgss.Oid supportedOid, org.ietf.jgss.Oid... supportedOids)Authenticateusernameusing the"gssapi-with-mic"authentication method, given a login context for the peer GSS machine and a list of supported OIDs.voidauthPassword(java.lang.String username, char[] password)Authenticateusernameusing the"password"authentication method and as a fallback basic challenge-response authentication..voidauthPassword(java.lang.String username, java.lang.String password)Authenticateusernameusing the"password"authentication method and as a fallback basic challenge-response authentication.voidauthPassword(java.lang.String username, PasswordFinder pfinder)Authenticateusernameusing the"password"authentication method and as a fallback basic challenge-response authentication.voidauthPassword(java.lang.String username, PasswordFinder pfinder, PasswordUpdateProvider newPasswordProvider)Authenticateusernameusing the"password"authentication method and as a fallback basic challenge-response authentication.voidauthPublickey(java.lang.String username)Authenticateusernameusing the"publickey"authentication method, with keys from some common locations on the file system.voidauthPublickey(java.lang.String username, java.lang.Iterable<KeyProvider> keyProviders)Authenticateusernameusing the"publickey"authentication method.voidauthPublickey(java.lang.String username, java.lang.String... locations)Authenticateusernameusing the"publickey"authentication method, with keys from one or morelocationsin the file system.voidauthPublickey(java.lang.String username, KeyProvider... keyProviders)Authenticateusernameusing the"publickey"authentication method.voidclose()Same asdisconnect().voiddisconnect()Disconnects from the connected SSH server.protected voiddoKex()Do key exchange.ConnectiongetConnection()java.nio.charset.CharsetgetRemoteCharset()Returns the character set used to communicate with the remote machine for certain strings (like paths).RemotePortForwardergetRemotePortForwarder()java.net.InetSocketAddressgetRemoteSocketAddress()Get Remote Socket Address from TransportTransportgetTransport()UserAuthgetUserAuth()booleanisAuthenticated()booleanisConnected()KeyProviderloadKeys(java.lang.String location)Returns aKeyProviderinstance created from a location on the file system where an unencrypted private key file (does not require a passphrase) can be found.KeyProviderloadKeys(java.lang.String location, char[] passphrase)Utility function for creating aKeyProviderinstance from given location on the file system.KeyProviderloadKeys(java.lang.String location, java.lang.String passphrase)Convenience method for creating aKeyProviderinstance from alocationwhere an encrypted key file is located.KeyProviderloadKeys(java.lang.String privateKey, java.lang.String publicKey, PasswordFinder passwordFinder)Creates aKeyProviderinstance from passed strings.KeyProviderloadKeys(java.lang.String location, PasswordFinder passwordFinder)Creates aKeyProviderinstance from given location on the file system.KeyProviderloadKeys(java.security.KeyPair kp)Creates aKeyProviderfrom suppliedKeyPair.voidloadKnownHosts()Attempts loading the user'sknown_hostsfile from the default locations, i.e.voidloadKnownHosts(java.io.File location)Adds aOpenSSHKnownHostsobject created from the specified location as a host key verifier.DirectConnectionnewDirectConnection(java.lang.String hostname, int port)Create aDirectConnectionchannel that connects to a remote address from the server.LocalPortForwardernewLocalPortForwarder(Parameters parameters, java.net.ServerSocket serverSocket)Create aLocalPortForwarderthat will listen based onparametersusing the boundserverSocketand forward incoming connections to the server; which will further forward them tohost:port.SCPFileTransfernewSCPFileTransfer()SFTPClientnewSFTPClient()StatefulSFTPClientnewStatefulSFTPClient()Stateful FTP client is required in order to connect to Serv-U FTP servers.protected voidonConnect()On connection establishment, also initializes the SSH transport viaTransport.init(java.lang.String, int, java.io.InputStream, java.io.OutputStream)anddoKex().X11ForwarderregisterX11Forwarder(ConnectListener listener)Register alistenerfor handling forwarded X11 channels.voidrekey()Does key re-exchange.voidsetRemoteCharset(java.nio.charset.Charset remoteCharset)Sets the character set used to communicate with the remote machine for certain strings (like paths)SessionstartSession()Opens asessionchannel.voiduseCompression()Addszlibcompression to preferred compression algorithms.-
Methods inherited from class net.schmizz.sshj.SocketClient
connect, connect, connect, connect, connect, connect, connectVia, connectVia, getConnectTimeout, getLocalAddress, getLocalPort, getRemoteAddress, getRemoteHostname, getRemotePort, getSocket, getSocketFactory, getTimeout, makeInetSocketAddress, setConnectTimeout, setSocketFactory, setTimeout
-
-
-
-
Field Detail
-
DEFAULT_PORT
public static final int DEFAULT_PORT
Default port for SSH- See Also:
- Constant Field Values
-
loggerFactory
protected final LoggerFactory loggerFactory
Logger
-
log
protected final org.slf4j.Logger log
-
trans
protected final Transport trans
Transport layer
-
auth
protected final UserAuth auth
ssh-userauthservice
-
conn
protected final Connection conn
ssh-connectionservice
-
remoteCharset
protected java.nio.charset.Charset remoteCharset
character set of the remote machine
-
-
Constructor Detail
-
SSHClient
public SSHClient()
Default constructor. Initializes this object usingDefaultConfig.
-
-
Method Detail
-
addHostKeyVerifier
public void addHostKeyVerifier(HostKeyVerifier verifier)
Add aHostKeyVerifierwhich will be invoked for verifying host key during connection establishment and future key exchanges.- Parameters:
verifier-HostKeyVerifierinstance
-
addAlgorithmsVerifier
public void addAlgorithmsVerifier(AlgorithmsVerifier verifier)
Add aAlgorithmsVerifierwhich will be invoked for verifying negotiated algorithms.- Parameters:
verifier-AlgorithmsVerifierinstance
-
addHostKeyVerifier
public void addHostKeyVerifier(java.lang.String fingerprint)
Add aHostKeyVerifierthat 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:
SecurityUtils.getFingerprint(java.security.PublicKey)
-
auth
public void auth(java.lang.String username, AuthMethod... methods) throws UserAuthException, TransportExceptionAuthenticateusernameusing 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(java.lang.String username, java.lang.Iterable<AuthMethod> methods) throws UserAuthException, TransportExceptionAuthenticateusernameusing 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(java.lang.String username, java.lang.String password) throws UserAuthException, TransportExceptionAuthenticateusernameusing 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(java.lang.String username, char[] password) throws UserAuthException, TransportExceptionAuthenticateusernameusing the"password"authentication method and as a fallback basic challenge-response authentication.. Thepasswordarray 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(java.lang.String username, PasswordFinder pfinder) throws UserAuthException, TransportExceptionAuthenticateusernameusing the"password"authentication method and as a fallback basic challenge-response authentication.- Parameters:
username- user to authenticatepfinder- thePasswordFinderto use for authentication- Throws:
UserAuthException- in case of authentication failureTransportException- if there was a transport-layer error
-
authPassword
public void authPassword(java.lang.String username, PasswordFinder pfinder, PasswordUpdateProvider newPasswordProvider) throws UserAuthException, TransportExceptionAuthenticateusernameusing the"password"authentication method and as a fallback basic challenge-response authentication.- Parameters:
username- user to authenticatepfinder- thePasswordFinderto use for authenticationnewPasswordProvider- thePasswordUpdateProviderto 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
public void authPublickey(java.lang.String username) throws UserAuthException, TransportExceptionAuthenticateusernameusing the"publickey"authentication method, with keys from some common locations on the file system. This method relies on~/.ssh/id_rsaand~/.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(java.lang.String username, java.lang.Iterable<KeyProvider> keyProviders) throws UserAuthException, TransportExceptionAuthenticateusernameusing the"publickey"authentication method.KeyProviderinstances can be created using any of the of theloadKeys()method provided in this class. In case multiplekeyProvidersare specified; authentication is attempted in order as long as the"publickey"authentication method is available.- Parameters:
username- user to authenticatekeyProviders- one or moreKeyProviderinstances- Throws:
UserAuthException- in case of authentication failureTransportException- if there was a transport-layer error
-
authPublickey
public void authPublickey(java.lang.String username, KeyProvider... keyProviders) throws UserAuthException, TransportExceptionAuthenticateusernameusing the"publickey"authentication method.KeyProviderinstances can be created using any of theloadKeys()method provided in this class. In case multiplekeyProvidersare specified; authentication is attempted in order as long as the"publickey"authentication method is available.- Parameters:
username- user to authenticatekeyProviders- one or moreKeyProviderinstances- Throws:
UserAuthException- in case of authentication failureTransportException- if there was a transport-layer error
-
authPublickey
public void authPublickey(java.lang.String username, java.lang.String... locations) throws UserAuthException, TransportExceptionAuthenticateusernameusing the"publickey"authentication method, with keys from one or morelocationsin the file system. In case multiplelocationsare 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(java.lang.String username, javax.security.auth.login.LoginContext context, org.ietf.jgss.Oid supportedOid, org.ietf.jgss.Oid... supportedOids) throws UserAuthException, TransportExceptionAuthenticateusernameusing 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-LoginContextfor 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
public void disconnect() throws java.io.IOExceptionDisconnects from the connected SSH server.SSHClientobjects are not reusable therefore it is incorrect to attempt connection after this method has been called. This method should be called from afinallyconstruct 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:
disconnectin classSocketClient- Throws:
java.io.IOException
-
getConnection
public Connection getConnection()
- Returns:
- the associated
Connectioninstance.
-
getRemoteSocketAddress
public java.net.InetSocketAddress getRemoteSocketAddress()
Get Remote Socket Address from Transport- Specified by:
getRemoteSocketAddressin interfaceRemoteAddressProvider- Returns:
- Remote Socket Address or null when not connected
-
getRemoteCharset
public java.nio.charset.Charset getRemoteCharset()
Returns the character set used to communicate with the remote machine for certain strings (like paths).- Returns:
- remote character set
-
getRemotePortForwarder
public RemotePortForwarder getRemotePortForwarder()
- Returns:
- a
RemotePortForwarderthat allows requesting remote forwarding over this connection.
-
getUserAuth
public UserAuth getUserAuth()
- Returns:
- the associated
UserAuthinstance. 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:
isConnectedin classSocketClient- Returns:
- whether connected.
-
loadKeys
public KeyProvider loadKeys(java.security.KeyPair kp)
Creates aKeyProviderfrom suppliedKeyPair.- Parameters:
kp- the key pair- Returns:
- the key provider ready for use in authentication
-
loadKeys
public KeyProvider loadKeys(java.lang.String location) throws java.io.IOException
Returns aKeyProviderinstance 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 thePasswordFinderargument 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 classpathjava.io.IOException- if the key file format is not known, if the file could not be read, etc.
-
loadKeys
public KeyProvider loadKeys(java.lang.String location, char[] passphrase) throws java.io.IOException
Utility function for creating aKeyProviderinstance from given location on the file system. Creates a one-offPasswordFinderusingPasswordUtils.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 classpathjava.io.IOException- if the key file format is not known, if the file could not be read, etc.
-
loadKeys
public KeyProvider loadKeys(java.lang.String location, PasswordFinder passwordFinder) throws java.io.IOException
Creates aKeyProviderinstance 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- thePasswordFinderthat can supply the passphrase for decryption (may benullin 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 classpathjava.io.IOException- if the key file format is not known, if the file could not be read, etc.
-
loadKeys
public KeyProvider loadKeys(java.lang.String location, java.lang.String passphrase) throws java.io.IOException
Convenience method for creating aKeyProviderinstance from alocationwhere an encrypted key file is located. CallsloadKeys(String, char[])with a character array created from the suppliedpassphrasestring.- Parameters:
location- location of the key filepassphrase- passphrase as a string- Returns:
- the key provider for use in authentication
- Throws:
java.io.IOException- if the key file format is not known, if the file could not be read etc.
-
loadKeys
public KeyProvider loadKeys(java.lang.String privateKey, java.lang.String publicKey, PasswordFinder passwordFinder) throws java.io.IOException
Creates aKeyProviderinstance 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- thePasswordFinderthat can supply the passphrase for decryption (may benullin 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 classpathjava.io.IOException- if the key file format is not known, etc.
-
loadKnownHosts
public void loadKnownHosts() throws java.io.IOExceptionAttempts loading the user'sknown_hostsfile from the default locations, i.e.~/.ssh/known_hostsand~/.ssh/known_hosts2on most platforms. Adds the resultingOpenSSHKnownHostsobject as a host key verifier. For finer control over which file is used, seeloadKnownHosts(File).- Throws:
java.io.IOException- if there is an error loading from both locations
-
loadKnownHosts
public void loadKnownHosts(java.io.File location) throws java.io.IOExceptionAdds aOpenSSHKnownHostsobject created from the specified location as a host key verifier.- Parameters:
location- location forknown_hostsfile- Throws:
java.io.IOException- if there is an error loading from any of these locations
-
newLocalPortForwarder
public LocalPortForwarder newLocalPortForwarder(Parameters parameters, java.net.ServerSocket serverSocket)
Create aLocalPortForwarderthat will listen based onparametersusing the boundserverSocketand 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
public DirectConnection newDirectConnection(java.lang.String hostname, int port) throws java.io.IOException
Create aDirectConnectionchannel 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:
java.io.IOException
-
registerX11Forwarder
public X11Forwarder registerX11Forwarder(ConnectListener listener)
Register alistenerfor 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- theConnectListenerthat should be delegated the responsibility of handling forwardedX11Forwarder.X11Channel's- Returns:
- an
X11Forwarderthat allows tostop actingon X11 requests from server
-
newSCPFileTransfer
public SCPFileTransfer newSCPFileTransfer()
- Returns:
- Instantiated
SCPFileTransferimplementation.
-
newSFTPClient
public SFTPClient newSFTPClient() throws java.io.IOException
- Returns:
- Instantiated
SFTPClientimplementation. - Throws:
java.io.IOException- if there is an error starting thesftpsubsystem- See Also:
StatefulSFTPClient
-
newStatefulSFTPClient
public StatefulSFTPClient newStatefulSFTPClient() throws java.io.IOException
Stateful FTP client is required in order to connect to Serv-U FTP servers.- Returns:
- Instantiated
SFTPClientimplementation. - Throws:
java.io.IOException- if there is an error starting thesftpsubsystem
-
rekey
public void rekey() throws TransportExceptionDoes key re-exchange.- Throws:
TransportException- if an error occurs during key exchange
-
setRemoteCharset
public void setRemoteCharset(java.nio.charset.Charset remoteCharset)
Sets the character set used to communicate with the remote machine for certain strings (like paths)- Parameters:
remoteCharset- remote character set ornullfor default
-
startSession
public Session startSession() throws ConnectionException, TransportException
Description copied from interface:SessionFactoryOpens asessionchannel. The returnedSessioninstance allowsexecuting a remote command,starting a subsystem, orstarting a shell.- Specified by:
startSessionin interfaceSessionFactory- Returns:
- the opened
sessionchannel - Throws:
ConnectionExceptionTransportException- See Also:
Session
-
useCompression
public void useCompression() throws TransportExceptionAddszlibcompression 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:
java.lang.ClassNotFoundException- ifJZlibis not in classpathTransportException- if an error occurs during renegotiation
-
onConnect
protected void onConnect() throws java.io.IOExceptionOn connection establishment, also initializes the SSH transport viaTransport.init(java.lang.String, int, java.io.InputStream, java.io.OutputStream)anddoKex().- Throws:
java.io.IOException
-
doKex
protected void doKex() throws TransportExceptionDo key exchange.- Throws:
TransportException- if error during kex
-
close
public void close() throws java.io.IOExceptionSame asdisconnect().- Specified by:
closein interfacejava.lang.AutoCloseable- Specified by:
closein interfacejava.io.Closeable- Throws:
java.io.IOException
-
-