java linux命令远程执行_java远程调用linux的命令或者脚本

最近写了一个docker微服务,此微服务需要在晚上12点时远程触发hadoop集群的一个hive离线计算任务,因此需要 远程调用linux shell

于是用到了ganymed-ssh2 这个库

Maven里的依赖如下:

ch.ethz.ganymed

ganymed-ssh2

build210

commons-lang

commons-lang

2.6

测试代码如下:

packagesshtest;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.io.UnsupportedEncodingException;importch.ethz.ssh2.ChannelCondition;importch.ethz.ssh2.Connection;importch.ethz.ssh2.Session;importch.ethz.ssh2.StreamGobbler;public classRemoteExecuteCommand

{//字符编码默认是utf-8

private static String DEFAULTCHART = "UTF-8";privateConnection conn;privateString ip;privateString userName;privateString userPwd;publicRemoteExecuteCommand()

{this.ip = "172.27.8.132";this.userName = "root";this.userPwd = "123456";

}publicBoolean login()

{boolean flg = false;try{

conn= new Connection(ip);

conn.connect();

flg=conn.authenticateWithPassword(userName, userPwd);

}catch(IOException e)

{

e.printStackTrace();

}returnflg;

}publicString execute(String cmd)

{

String result= "";try{if(login())

{

System.out.println("hihiihihih2222:");

Session session=conn.openSession();session.requestPTY("bash");

session.startShell();

PrintWriter out= newPrintWriter(session.getStdin());

out.println(cmd);

out.flush();out.println("exit");out.close();

session.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF |ChannelCondition.EXIT_STATUS,60000);System.out.println("exec has finished!");

session.close();

conn.close();

}

}catch(

IOException e)

{

e.printStackTrace();

}returnresult;

}}

packagesshtest;

public classSshTest

{public static voidmain(String[] args)

{RemoteExecuteCommand rec= newRemoteExecuteCommand();

String result= rec.execute("sh /home/mongo-hive-hbase/Hive_HistClientsInfoAnalysis.sh");return;

}

}

参考:

http://www.cnblogs.com/-wangjiannan/p/3751330.html

http://www.programcreek.com/

BTW,用此库调用shell脚本时,因为微服务不需要一直挂着等脚本,因此,需要用nohup的方式来让shell脚本后台执行,这样即使终端关闭也不会对执行有影响。

由于是docker服务,在布署docker的时候会起两个docker 同时起,导致到了12点会触发执行两次shell脚本,这个问题定位了两天。。。。本地windows 下Eclipse试

着去触发都好好的,布署到docker上就是会触发两次,于是,怀疑

1.ganymed ssh2库接口的使用问题, 从session.execCommand(cmd) 这种调用方式换成了

session.requestPTY("bash");

session.startShell();

这种方式,还是一样。

2. 怀疑windows /linux环境的不同所导致 , 结果用以上sshtest的测试程序放在本地linux机器上试仍然ok

3. 怀疑是docker环境的问题,把以上sshtest打包成docker,在本地手动执行(本地环境只会起一个docker),继续ok

4.怀疑人生。。。。。

5. 最后绝望之前猛然发现docker get pods -o wide |grep xxx,发现有两个在执行,把这事儿给忘记了。。

不过总归是搞定了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值