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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值