导入必要的jar包
ch.ethz.ganymed
ganymed-ssh2
build250
public static void executeCommand(String command,String host,String username,String password){
Connection conn = null;
Session session = null;
try {
logger.info("执行linux命令:{},host:{}",command,host);
conn = new Connection(host);
conn.connect();
boolean flg = conn.authenticateWithPassword(username, password);
if(flg){
session = conn.openSession();
session.requestPTY("bash");
session.startShell();
PrintWriter out = new PrintWriter(session.getStdin());
out.println(command);
out.flush();
out.println("exit");
out.close();
session.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,
60000);
}else{
logger.info("连接host{}失败",host);
}
} catch (IOException e) {
logger.info("host{}执行命令:{}出现异常"+e,host,command);
}finally {
session.close();
conn.close();
}
}