java 连接远程服务器_java连接远程服务器并执行命令

导入必要的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();

}

}


版权声明:本文为weixin_39528000原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。