Using JCABI-SSH to manipulate SSH commands in Java
If we want to connect SSH remotely in Java code and execute some shell commands, we can use the small framework of jcabi-ssh, which is very convenient to write in pure java. Here's how to use it.
Depend on
Java framework, depending on the package must be JAR file, jar package address Http://repo1.maven.org/maven2/com/jcabi/jcabi-ssh/1.1/jcabi-ssh-1.1.jar, if using MAVEN management , you can add dependencies:
<dependency> <groupId>com.jcabi</groupId> <artifactId>jcabi-ssh</artifactId> <version>1.1</version> </dependency>
Version 2.0, author not officially released
<repositories> <repository> <id>oss.sonatype.org</id> <url>https://oss.sonatype.org/content/repositories/snapshots/</url> </repository> </repositories> <dependencies> <dependency> <groupId>com.jcabi</groupId> <artifactId>jcabi-ssh</artifactId> <version>2.0-SNAPSHOT</version> </dependency> </dependencies>
code example
The code is simple, and the example is as follows:
String hello = new Shell.Plain( new SSH( "ssh.example.com", 22, "yegor", "-----BEGIN RSA PRIVATE KEY-----...") ).exec("echo ‘Hello, world!‘");
Note that the private key is the local private key string, Linux words in the/home/yourname/.ssh in the Id_rsa file, the contents of all copy into the method, including -----BEGIN RSA Private key-----, -----END RSA PRIVATE KEY----- These two lines.
To realize the native private key login, but also to copy the local public key to the target machine, the public key in the. SSH folder in the Id_rsa.pub file, the text is all copied into the target machine/home/yourname/.ssh/authorized_keys file, This allows the user to implement a password-free SSH login target machine.
The following is a more complex scenario, using SSH to upload a file to the server, and then grep the content to display it.
Shell shell = new SSH( "ssh.example.com", 22, "yegor", "-----BEGIN RSA PRIVATE KEY-----..." ); File file = new File("/tmp/data.txt"); new Shell.Safe(shell).exec( "cat > d.txt && grep ‘hello‘ d.txt", new FileInputStream(file), Logger.stream(Level.INFO, this), Logger.stream(Level.WARNING, this) );
SSH
This class implements the Shell
interface, which in fact is a method exec
, the Exec method receives four parameters:
interface Shell { int exec( String cmd, InputStream stdin, OutputStream stdout, OutputStream stderr ); }
Shell.safe
Shell.Safe
Some encapsulation of the native Shell object is made, and if the exec
return value of the method is not 0, an exception is thrown. Depending on the return value, you can confirm that the shell command executed successfully.
Continue reading,
Using JCABI-SSH to manipulate SSH commands in Java