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中执行Shell命令只需要几行代码,可以使用jcabi-ssh
。
jcabi-ssh
是 JSch
的一个便利包装,JSch
是一个著名的纯 Java 实现的 SSH2。
这是一个更复杂的场景,我通过 SSH 上传一个文件,然后读取它的 grepped 内容。
类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 上。如果您有任何问题,请提交一个问题(issue)。我会尽力帮助您。
Translated by ChatGPT gpt-3.5-turbo/42 on 2023-11-28 at 15:07