First write a test script test.sh on the remote server and give the executable permission: chmod +x test.sh
#!/bin/bash echo ' test22 ' echo $
$ $ is the first parameter passed in the script, and our console prints this parameter
To create a new MAVEN project, add dependencies:
<dependency> <groupId>org.jvnet.hudson</groupId> <artifactid>ganymed-ssh2</artifactid > <version>build210-hudson-1</version> </dependency>
Write a tool class:
import java.io.ioexception; import java.io.inputstream; import java.nio.charset.charset; import ch.ethz.ssh2.connection; import ch.ethz.ssh2.session; public class remoteshelltool { private connection conn; private String ipAddr; private String charset = Charset.defaultcharset (). toString (); private string username; private String password; public remoteshelltool (string ipaddr, string username, string password, string CharSet) { this.ipaddr = ipaddr; this.userName = userName; this.password = password; if ( Charset != null) { this.charset = charset; } } public boolean Login () throws ioexception { conn = new connection (IPADDR); Conn.connect (); // connection return Conn.authenticatewithpassword (Username, password); // Certification } public string exec (STRING&NBSP;CMDS) { inputstream in = null; string result = ""; try { if (This.login ()) { Session Session = conn.opensession (); // Open a session session.execcommand (CMDS); in = session.getstdout (); result = this.processstdout (In, this.charset); session.close (); conn.close (); } } catch (IOEXCEPTION&NBSP;E1) { e1.printstacktrace (); } return result; } public string processstdout (inputstream in, string CharSet) { byte[] buf = new byte[1024]; stringbuffer sb = new stringbuffer (); try { while (In.read (BUF) != -1) { sb.append (new string (buf, charset)); } } catch (ioexception e) { e.printstacktrace (); } return sb.tostring (); } /** * @param Args */ public static void main (String[] args) { Remoteshelltool tool = new remoteshelltool ("192.168.27.41", "Hadoop", "Hadoop", "Utf-8"); string result = tool.exec ("./test.sh xiaojun"); System.out.print (Result); } }
The main function executes the./test.sh Xiaojun This command, the console prints out:
test22
Xiaojun
This simple remote call Shell demo is done.
This article from "in order to finger that direction" blog, declined reprint!
Java Connection SSH Call Shell