import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class SSHUtil {
private Channel channel;
private Session session = null;
private int timeout = 60000;
public SSHUtil(final String ipAddress, int port,final String username, final String password) throws Exception {
JSch jsch = new JSch();
this.session = jsch.getSession(username, ipAddress, port);
this.session.setPassword(password);
this.session.setConfig("StrictHostKeyChecking", "no");
this.session.setTimeout(this.timeout);
this.session.connect();
this.channel = this.session.openChannel("shell");
this.channel.connect(1000);
}
public String runShell(String cmd, String charset) throws Exception {
String temp = null;
InputStream instream = null;
OutputStream outstream = null;
try {
instream = this.channel.getInputStream();
outstream = this.channel.getOutputStream();
outstream.write(cmd.getBytes());
outstream.flush();
TimeUnit.SECONDS.sleep(2);
if (instream.available() > 0) {
byte[] data = new byte[instream.available()];
int nLen = instream.read(data);
if (nLen < 0) {
throw new Exception("network error.");
}
temp = new String(data, 0, nLen, "UTF-8");
}
} finally {
outstream.close();
instream.close();
}
return temp;
}
public void close() {
this.channel.disconnect();
this.session.disconnect();
}
public static void main(final String[] args) throws Exception {
//shutdown.sh
SSHUtil sshUtil = new SSHUtil("136.16.19.82",22, "root", "123456");
String res = sshUtil.runShell("/usr/apache-tomcat-7.0.47/bin/startup.sh \n", "utf-8");
System.out.println(res);
sshUtil.close();
}
}