Simple Java SSH Client

The following text is a partial translation of the original English article, performed by ChatGPT (gpt-3.5-turbo) and this Jekyll plugin:

Выполнение команды оболочки через SSH можно выполнить на Java всего за несколько строк, используя jcabi-ssh.

jcabi-ssh - это удобная оболочка для JSch, широко известной чистой реализации SSH2 на языке Java.

Вот более сложный сценарий, в котором я загружаю файл по SSH, а затем считываю его отфильтрованное содержимое с помощью команды grep:

Класс SSH, реализующий интерфейс Shell, имеет только один метод exec. Этот метод принимает четыре аргумента:

Я думаю, что очевидно, о чем эти аргументы.

Также есть несколько удобных декораторов, которые упрощают работу с простыми командами.

Shell.Safe decorates an instance of Shell and throws an exception if the exec exit code is not equal to zero. This may be very useful when you want to make sure that your command executed successfully, but don’t want to duplicate if/throw in many places of your code.

Shell ssh = new Shell.Safe(
  new SSH(
    "ssh.example.com", 22,
    "yegor", "-----BEGIN RSA PRIVATE KEY-----..."
  )
);

Shell.Verbose

Shell.Verbose decorates an instance of Shell and copies stdout and stderr to the slf4j logging facility (using jcabi-log). Of course, you can combine decorators, for example:

Shell ssh = new Shell.Verbose(
  new Shell.Safe(
    new SSH(
      "ssh.example.com", 22,
      "yegor", "-----BEGIN RSA PRIVATE KEY-----..."
    )
  )
);

Shell.Plain

Shell.Plain is a wrapper of Shell that introduces a new exec method with only one argument, a command to execute. It also doesn’t return an exit code, but stdout instead. This should be very convenient when you want to execute a simple command and just get its output (I’m combining it with Shell.Safe for safety):

String login = new Shell.Plain(new Shell.Safe(ssh)).exec("whoami");

Download

В вашем проекте Maven вам понадобится только одна зависимость jcabi-ssh.jar (получите ее последнюю версию в Maven Central).

Проект находится в GitHub. Если у вас возникли проблемы, просто создайте запрос. Я постараюсь помочь.

Translated by ChatGPT gpt-3.5-turbo/42 on 2023-11-28 at 15:08

sixnines availability badge   GitHub stars