java远程调用shell脚本 脚本执日志报command not found

        java远程调用shell脚本,提示命令找不到command not found异常,但是使用同一个用户登录服务器后在sh执行同一个脚本,并没有该提示。经过百度好像是因为环境变量未加载。需要在远程调用脚本的命令前面加上 ". ~/.bash_profile && source /etc/profile" 一段话。

例如以前脚本调用命令"sh /xxx/xx.sh"

修改后为". ~/.bash_profile && source /etc/profile && sh /xxx/xx.sh"

这里注意,前面的“.”不要忘记。

        java远程调用工具类:

public static List<String> jschExecCommand(String ip, String username, String password, String cmd){
    JSch jSch = new JSch();
    Session session = null;
    BufferedReader br = null;
    InputStream errStream = null;
    ChannelExec exec = null;
    try{
        
        session = jSch.getSession(username,ip);
        session.setPassword(password);
        Properties properties = new Properties();
        properties.put("StrictHostKeyChecking","no");
        session.setConfig(properties);
        session.connect(10000);
        logger.info("-----远程链接成功 ip={}",ip);
        exec = (ChannelExec)session.openChannel("exec");
        exec.setCommand(cmd);
        exec.connect();
        br = new BufferedReader(new InputStreamReader(exec.getInputStread()));
        logger.info("-----命令执行日志如下:");
        List<String> r = new ArrayList<>();
        String line = "";
        while((line = br.readLine()) != null){
            r.add(line);
            logger.info(line);
        }
        
        //打印错误日志,这里使用InputStream直接打印,转换为字符流会出现阻塞问题
        errStream = exec.getErrStream();
        StringBuffer sb = new StringBuffer();
        byte[] buf = new byte[2048];
        while(errStream.read(buf) != -1){
            sb.append(buf);
        }
        logger.info("-----命令执行错误日志如下:{}",sb);
        
        return r;
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        
        if(errStream != null){
            try{
                errStream.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        if(br != null){
            try{
                br.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        if(exec != null){
            exec.disconnect();
        }
        if(session != null){
            session.disconnect();
        }

    }
    return null;
}

该远程调用shell工具类使用JSch实现,其他实现方式类似。

JSch的maven依赖:
<dependency>

        <groupId>com.jcraft</groupId>

        <artifactId>jsch</artifactId>

        <version>0.1.50</version>

</dependency>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值