This is an AMP version of the article, its original content can be found here.
Simple Java SSH Client
An execution of a shell command via SSH can be done in
Java, in just a few lines, using
a convenient wrapper of
a well-known pure Java implementation of SSH2.
Here is a more complex scenario, where I upload a file via SSH and then read back its grepped content:
SSH, which implements interface
Shell, has only one method,
This method accepts four arguments:
I think it's obvious what these arguments are about.
There are also a few convenient decorators that make it easier to operate with simple commands.
Shell.Safe decorates an instance of
throws an exception
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.Verbose decorates an instance of
Shell and copies
stderr to the slf4j logging facility (using
jcabi-log). Of course, you can combine
decorators, for example:
Shell.Plain is a wrapper of
Shell that introduces a new
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):
You need a single dependency
in your Maven project
(get its latest version in Maven Central):
The project is in GitHub. If you have any problems, just submit an issue. I'll try to help.