Import java.io.IOException;
Import Java.io.InputStream;
Import java.io.UnsupportedEncodingException;
Import Java.nio.charset.Charset;
Import Org.apache.commons.io.IOUtils;
Import ch.ethz.ssh2.ChannelCondition;
Import ch.ethz.ssh2.Connection;
Import ch.ethz.ssh2.Session;
Import Ch.ethz.ssh2.StreamGobbler;
public class Remoteshellexecutor {private Connection conn;
/** Remote Machine IP */private String IP;
/** User name */private String osusername;
/** Password */private String password;
Private String charset = Charset.defaultcharset (). toString ();
private static final int time_out = 1000 * 5 * 60; /** * constructor * @param IP * @param usr * @param pasword/public Remoteshellexecutor (Stri
ng IP, string usr, string pasword) {this.ip = IP;
This.osusername = usr;
This.password = Pasword; /** * Login * @return * @throws IOException/Private Boolean login () throws IOException {conn = new Connection (IP);
Conn.connect ();
Return Conn.authenticatewithpassword (osusername, password); /** * Execute Script * * @param cmds * @return * @throws Exception * * public int exec (St
Ring Cmds) throws Exception {InputStream stdOut = null;
InputStream STDERR = null;
String outstr = "";
String outerr = "";
int ret =-1; try {if (login ()) {//Open a new {@link session} in this connection sessions session =
Conn.opensession ();
Execute a command on the remote machine.
Session.execcommand (CMDS);
StdOut = new Streamgobbler (Session.getstdout ());
outstr = Processstream (StdOut, CharSet);
STDERR = new Streamgobbler (Session.getstderr ());
Outerr = Processstream (STDERR, CharSet); SEssion.waitforcondition (Channelcondition.exit_status, time_out);
System.out.println ("outstr=" + outstr);
System.out.println ("outerr=" + outerr);
ret = Session.getexitstatus (); else {throw new Exception ("Log on to remote machine failed" + IP);//Custom Exception class implementation abbreviated}} finally {if (conn!= null)
{Conn.close ();
} ioutils.closequietly (StdOut);
ioutils.closequietly (STDERR);
return ret; }/** * @param in * @param charset * @return * @throws IOException * @throws Unsupportedenc Odingexception */private string Processstream (InputStream in, String charset) throws Exception {byte[
] buf = new byte[1024];
StringBuilder sb = new StringBuilder ();
while (In.read (BUF)!=-1) {Sb.append (new String (BUF, CharSet)); Return SB.TOSTRING (); public static void Main (String args[]) throws Exception {Remoteshellexecutor executor = new Remoteshellexe
Cutor ("172.16.22.187", "root", "123456");
The execution mytest.sh parameter is the Java Know dummy System.out.println (Executor.exec ("./mtreceiver.sh start")); }
}