Original: http://www.cnblogs.com/enshrineZither/p/3793459.html
1 package com.pasier.xxx.util;
2 3 Import java.io.IOException;
4 Import Java.io.InputStream;
5 Import Java.nio.charset.Charset;
6 7 Import Org.slf4j.Logger;
8 Import Org.slf4j.LoggerFactory;
9 Import ch.ethz.ssh2.ChannelCondition;
Import ch.ethz.ssh2.Connection;
Import ch.ethz.ssh2.Session;
Import Ch.ethz.ssh2.StreamGobbler; The public class Rmtshellexecutor {The private static final Logger LOG = Loggerfactory.getlogger (rmtshellexe
Cutor.class);
Private Connection Conn;
Private String IP;
Private String usr;
Private String Psword;
The private String charset = Charset.defaultcharset (). toString ();
The private static final int time_out = 1000 * 5 * 60;
Rmtshellexecutor Public (string IP, String usr, string ps) {this.ip = IP;
this.usr = usr;
This.psword = PS; The private Boolean login () throws IOException {conn = new Connection (IP);
Conn.connect ();
Return Conn.authenticatewithpassword (usr, psword);
Throws public string exec (string cmds) IOException {InputStream stdOut = null;
InputStream STDERR = null;
A String outstr = "";
A String Outerr = "";
int ret =-1;
A try {if (login ()) {conn.opensession session = ();
Session.execcommand (CMDS);
StdOut = new Streamgobbler (Session.getstdout ());
Wuyi outstr = Processstream (StdOut, CharSet);
Log.info ("Caijl:[info] outstr=" + outstr);
STDERR = new Streamgobbler (Session.getstderr ());
Outerr = Processstream (STDERR, CharSet);
Log.info ("Caijl:[info] outerr=" + outerr);
Session.waitforcondition (Channelcondition.exit_status, time_out); 57 ret = Session.getexitstatus ();
Log.error} else {"Caijl:[info] SSH2 Login failure:" + IP);
throw new IOException ("Ssh2_err");
The} is finally {conn!= null) {conn.close ();
The IF (stdOut!= null) stdout.close ();
if (STDERR!= null) stderr.close ();
outstr; $ + Private String Processstream (InputStream in, String charset) throws IOException {byte[]
BUF = new byte[1024];
StringBuilder sb = new StringBuilder ();
while (In.read (BUF)!=-1) {Bayi sb.append (new String (BUF, CharSet));
Sb.tostring ();
string[public static void Main (] args) {The "root" of the String usr = ";" Password String = "12345";
A String ServerIP = "11.22.33.xx";
Shpath = "/root/ab.sh";
Rmtshellexecutor exe = new Rmtshellexecutor (serverip, usr, password);
Outinf String;
The try {outinf = exe.exec ("sh" + shpath + "xn");
System.out.println ("outinf=" + outinf); M catch (IOException e) {e.printstacktrace (); 102} 103} 104 105}