importch.ethz.ssh2.Connection;importch.ethz.ssh2.Session;importch.ethz.ssh2.StreamGobbler;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importjava.io.BufferedReader;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.util.ArrayList;importjava.util.List;public classBashUtil {private Logger logger = LoggerFactory.getLogger(BashUtil.class);privateString hostname;privateString username;privateString password;private intport;privateConnection conn;privateBashUtil() {
}publicBashUtil(String hostname, String username, String password) {this(hostname, username, password, 22);
}publicBashUtil(String hostname, String username, String password, Integer port) {this.hostname =hostname;this.username =username;this.password =password;if (port == null) {
port= 22;
}else{this.port =port;
}
}/*** 创建连接并认证
*@return
*/
publicBoolean connection() {try{
conn= newConnection(hostname, port);
conn.connect();boolean isAuthenticated =conn.authenticateWithPassword(username, password);returnisAuthenticated;
}catch(Exception e) {
e.printStackTrace();return false;
}
}/*** 关闭连接*/
public voidclose() {try{
conn.close();
conn= null;
}catch(Exception e) {
e.printStackTrace();
}
}/*** 执行shell命令
*@paramcommand
*@return
*/
public Listcommand(String command) {if (conn == null && !connection()) {
logger.error("Authentication failed.");return null;
}
List result = new ArrayList();try{
Session sess=conn.openSession();
sess.execCommand(command);
InputStream stdout= newStreamGobbler(sess.getStdout());
InputStream stderr= newStreamGobbler(sess.getStderr());
BufferedReader br_out= new BufferedReader(new InputStreamReader(stdout, "utf-8"));
BufferedReader br_err= new BufferedReader(new InputStreamReader(stderr, "utf-8"));
StringBuffer sb_err= newStringBuffer();
String line= null;while ((line = br_out.readLine()) != null) {
result.add(line.trim());
}while ((line = br_err.readLine()) != null) {
sb_err.append(line+ "\n");
}if(isNotEmpty(sb_err.toString())) {
logger.error(sb_err.toString());return null;
}returnresult;
}catch(Exception e) {
e.printStackTrace();
}return null;
}private static booleanisEmpty(String content) {if (content == null) {return true;
}else{return "".equals(content.trim()) || "null".equalsIgnoreCase(content.trim());
}
}private static booleanisNotEmpty(String content) {return !isEmpty(content);
}public static voidmain(String[] args){
String hostname= "192.168.123.234"; //此处根据实际情况,换成自己需要访问的主机IP
String userName = "root";
String password= "password";
Integer port= 22;
String command= "cd /home/miracle&&pwd&&ls&&cat luna.txt";
BashUtil bashUtil= newBashUtil(hostname, userName, password, port);
List resultList =bashUtil.command(command);
StringBuffer result= new StringBuffer("");
resultList.forEach(str-> result.append(str + "\n"));
System.out.println("执行的结果如下: \n" +result.toString());
}
}