Class SshClient

java.lang.Object
org.metricshub.ssh.SshClient
All Implemented Interfaces:
AutoCloseable

public class SshClient extends Object implements AutoCloseable
SSH Client that lets you perform basic SSH operations
  1. Instantiate the SSH Client
  2. Connect
  3. Authenticate
  4. Enjoy!
  5. DISCONNECT!
Author:
Bertrand
  • Constructor Details

    • SshClient

      public SshClient(String pHostname)
      Creates an SSHClient to connect to the specified hostname
      Parameters:
      pHostname - Hostname of the SSH server to connect to
    • SshClient

      public SshClient(String pHostname, String pLocale)
      Creates an SSHClient to connect to the specified hostname
      Parameters:
      pHostname - Hostname of the SSH server to connect to
      pLocale - Locale used on the remote server (e.g. zh_CN.utf8)
    • SshClient

      public SshClient(String pHostname, Charset pCharset)
      Creates an SSHClient to connect to the specified hostname
      Parameters:
      pHostname - Hostname of the SSH server to connect to
      pCharset - Charset used on the remote server
  • Method Details

    • connect

      public void connect() throws IOException
      Connects the SSH Client to the SSH server
      Throws:
      IOException
    • connect

      public void connect(int timeout) throws IOException
      Connects the SSH client to the SSH server using the default SSH port (22).
      Parameters:
      timeout - Timeout in milliseconds
      Throws:
      IOException - when connection fails or when the server does not respond (SocketTimeoutException)
    • connect

      public void connect(int timeout, int port) throws IOException
      Connects the SSH client to the SSH server using a specified SSH port.
      Parameters:
      timeout - Timeout in milliseconds
      port - SSH server port.
      Throws:
      IOException - when connection fails or when the server does not respond (SocketTimeoutException)
    • disconnect

      @Deprecated public void disconnect()
      Deprecated.
      (since = "3.14.00", forRemoval = true)
      Disconnects the SSH Client from the SSH server

      Note: This is important! Otherwise, the listener thread will remain running forever! Use a try with resource instead or the close() instead.

    • close

      public void close()
      Disconnects the SSH Client from the SSH server

      Note: This is important! Otherwise, the listener thread will remain running forever!

      Specified by:
      close in interface AutoCloseable
    • authenticate

      @Deprecated public boolean authenticate(String username, String privateKeyFile, String password) throws IOException
      Deprecated.
      (since = "3.14.00", forRemoval = true)
      Authenticate the SSH Client against the SSH server using a private key
      Parameters:
      username -
      privateKeyFile -
      password -
      Returns:
      a boolean stating whether the authentication worked or not
      Throws:
      IOException
    • authenticate

      public boolean authenticate(String username, File privateKeyFile, char[] password) throws IOException
      Authenticate the SSH Client against the SSH server using a private key
      Parameters:
      username -
      privateKeyFile -
      password -
      Returns:
      a boolean stating whether the authentication worked or not
      Throws:
      IOException
    • authenticate

      @Deprecated public boolean authenticate(String username, String password) throws IOException
      Deprecated.
      (since = "3.14.00", forRemoval = true)
      Authenticate the SSH Client against the SSH server using a password
      Parameters:
      username -
      password -
      Returns:
      a boolean stating whether the authentication worked or not
      Throws:
      IOException
    • authenticate

      public boolean authenticate(String username, char[] password) throws IOException
      Authenticate the SSH Client against the SSH server using a password
      Parameters:
      username -
      password -
      Returns:
      a boolean stating whether the authentication worked or not
      Throws:
      IOException
    • authenticate

      public boolean authenticate(String username) throws IOException
      Authenticate the SSH Client against the SSH server using NO password
      Parameters:
      username -
      Returns:
      a boolean stating whether the authentication worked or not
      Throws:
      IOException
    • readFileAttributes

      public String readFileAttributes(String filePath) throws IOException
      Return information about the specified file on the connected system, in the same format as the PSL function file()
      Parameters:
      filePath - Path to the file on the remote system
      Throws:
      IOException
    • fileSize

      public long fileSize(String filePath) throws IOException
      Returns the file size.
      Parameters:
      filePath - Path to the file on the remote system
      Returns:
      the file size
      Throws:
      IOException - if the file does not exist
    • listFiles

      public List<SshClient.FileEntry> listFiles(String remoteDirectoryPath, String regExpFileMask, boolean includeSubfolders) throws IOException
      List the regular files of the specified directory through SFTP. Symbolic links to regular files are followed: the entry carries the size and modification time of the target. Dangling links are skipped.
      Parameters:
      remoteDirectoryPath - The path to the directory to list on the remote host
      regExpFileMask - A regular expression that the names of the listed files must contain (case-insensitive, Matcher.find()); null or empty to list every file
      includeSubfolders - Whether to list subdirectories as well (symbolic links to directories are not followed, and no more than 15 levels are listed)
      Returns:
      The files of the specified directory
      Throws:
      IOException - When something bad happens while communicating with the remote host
      IllegalStateException - If called while not yet connected
    • listSubdirectories

      public List<String> listSubdirectories(String remoteDirectoryPath, String regExpMask) throws IOException
      List the subdirectories of the specified directory through SFTP. Symbolic links to directories are followed and listed; dangling links are skipped. The mask is checked before a link is followed.
      Parameters:
      remoteDirectoryPath - The path to the directory to list on the remote host
      regExpMask - A regular expression that the names of the listed subdirectories must contain (case-insensitive, Matcher.find()); null or empty to list every subdirectory
      Returns:
      The paths of the subdirectories: the specified directory, a slash and the subdirectory name
      Throws:
      IOException - When something bad happens while communicating with the remote host
      IllegalStateException - If called while not yet connected
    • readFile

      public String readFile(String remoteFilePath, Long readOffset, Integer readSize) throws IOException
      Read the specified file over the SSH session that was established.
      Parameters:
      remoteFilePath - Path to the file to be read on the remote host
      readOffset - Offset to read from
      readSize - Amount of bytes to be read
      Returns:
      The content of the file read
      Throws:
      IOException - when something gets wrong while reading the file (we get disconnected, for example, or we couldn't read the file)
      IllegalStateException - when the session hasn't been properly authenticated first
    • removeFile

      public void removeFile(String[] remoteFilePathArray) throws IOException
      Removes a list of files on the remote system.
      Parameters:
      remoteFilePathArray - Array of paths to the files to be deleted on the remote host
      Throws:
      IOException - when something bad happens while deleting the file
      IllegalStateException - when not connected and authenticated yet
    • removeFile

      public void removeFile(String remoteFilePath) throws IOException
      Removes the specified file on the remote system.
      Parameters:
      remoteFilePath -
      Throws:
      IOException
      IllegalStateException
    • executeCommand

      public SshClient.CommandResult executeCommand(String command) throws IOException
      Executes a command through the SSH connection
      Parameters:
      command - The command to be executed
      Returns:
      a CommandResult object with the result of the execution
      Throws:
      IllegalStateException - when the connection is not established first
      IOException - when there is a problem while communicating with the remote system
    • executeCommand

      public SshClient.CommandResult executeCommand(String command, int timeout) throws IOException
      Executes a command through the SSH connection
      Parameters:
      command - The command to be executed
      timeout - Milliseconds after which the command is considered failed
      Returns:
      a CommandResult object with the result of the execution
      Throws:
      IllegalStateException - when the connection is not established first
      IOException - when there is a problem while communicating with the remote system
    • interactiveSession

      public void interactiveSession(InputStream in, OutputStream out) throws IOException, InterruptedException
      Starts an interactive session.
      Parameters:
      in - Where the input is coming from (typically System.in)
      out - Where the output has to go (e.g. System.out)
      Throws:
      IllegalStateException - when not connected and authenticated
      IOException - in case of communication problems with the host
      InterruptedException - when a thread is interrupted
    • scp

      public void scp(String localFilePath, String remoteFilename, String remoteDirectory, String fileMode) throws IOException
      Copy a file to the remote host through SCP
      Parameters:
      localFilePath -
      remoteFilename -
      remoteDirectory -
      fileMode -
      Throws:
      IOException
    • openSession

      public void openSession() throws IOException
      Open a SSH Session.
      Throws:
      IOException - When an I/O error occurred.
    • openTerminal

      public void openTerminal() throws IOException
      Open a Terminal request for a wiiiiide terminal, with no ECHO (see https://tools.ietf.org/html/rfc4254#section-8)
      Throws:
      IOException - When an I/O error occurred.
    • write

      public void write(String text) throws IOException
      Write into the SSH session.
      Parameters:
      text - The text to be written.
      Throws:
      IOException - When an I/O error occurred.
    • read

      public Optional<String> read(int size, int timeout) throws IOException
      Read the stdout and stderr from the SSH session.
      Parameters:
      size - The buffer size of stdout and/or stderr to be read. (If less than 0 all data)
      timeout - Timeout in seconds
      Returns:
      An optional with all the data read (stdout and stderr). Empty if nothing was read.
      Throws:
      IOException - When an I/O error occurred.
    • checkIfSessionOpened

      public void checkIfSessionOpened()
      Check if the SSH session exists.