Connect to the remote server using ganymed SSH-2 for Java, and then execute the shell command;
First, we add a method to execute the shell command in the previous Commandrunner class, as shown in the following example:
public static string Execshellscript (string host, string username, string password, string cmd, int port) throws IO
Exception {if (logger.isinfoenabled ()) {Logger.info ("running SSH cmd [+ cmd +]");
} Connection conn = null;
Session sess = NULL;
InputStream stdout = null;
BufferedReader br = null;
StringBuffer buffer = new StringBuffer ("exec result:"); Buffer.append (System.getproperty ("Line.separator"));/newline try {conn = getopenedconnection (host, username, password,
Port);
Sess = Conn.opensession ();
Sess.execcommand (CMD);
stdout = new Streamgobbler (Sess.getstdout ());
br = new BufferedReader (new InputStreamReader (stdout)); while (true) {//Attention:do not comment this block, or you'll hit//NullPointerException/when
are trying to read exit status String = Br.readline ();
if (line = = null) break;
Buffer.append (line); Buffer.append (System.getproperty ("Line.separator);//NewLine if (logger.isinfoenabled ()) {logger.info (line);
}}} finally {Sess.close ();
Conn.close ();
return buffer.tostring ();
}
Test code:
public static void Main (string[] args) {
String cmd = "uname-a";
try {
String info = commandrunner.execshellscript ("172.16.18.141", "root",
"123456", cmd,22);
SYSTEM.OUT.PRINTLN ("info is:" +info);
} catch (IOException e) {
e.printstacktrace ();
}
}
Execution results
Log4j:warn No Appenders could is found for logger (Com.ssh2.shell.ganymed.CommandRunner).
Log4j:warn Please initialize the log4j system properly.
Log4j:warn http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Info is:exec Result:
Linux localhost.localdomain 2.6.32-220.el6.x86_64 #1 SMP Wed Nov 9 08:03:13 EST x86_64 x86_64 x86_64 gnu/linux
At this point, the simple method of connecting the remote server to execute the shell command is implemented.