Java调用shell脚本

public class ShellTest {


    private String callScript( String... workspace) {
        try {
            File dir = null;
            if (workspace[0] != null) {
                dir = new File(workspace[0]);
                System.out.println(workspace[0]);
            }
           // String[] evnp = {"val=2", "call=Bash Shell"};
            Process process = Runtime.getRuntime().exec("./invokeJ.sh", null, dir);
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = input.readLine()) != null) {
                result.append(line);
                result.append("\n");
            }
            input.close();
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "invoke error!";
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ShellTest call = new ShellTest();
        System.err.println(call.callScript("/export/data/shell"));
    }

}

shell脚本的路径和内容如下:

执行结果:

下面是我在服务中封装的方法

private void invokeCommand(final HttpExchange httpExchange) {
        logger.info("invoke command service start!");
        String requestBody = IOUtil.readStream(httpExchange.getRequestBody());
        CommandDefinition command = JSON.parseObject(requestBody, CommandDefinition.class);
        Assert.checkNonNull(command);
        Assert.check(StringUtils.isBlank(command.getCommand()), "command is null");
        Assert.check(StringUtils.isBlank(command.getDir()), "dir is null");
        logger.info("invoke command request body:{}", JSONObject.toJSONString(command));
        String result = executeCommand(command);
        logger.info("invoke command result:{}", result);
    }

    private String executeCommand(CommandDefinition command) {
        try {
            File dirTmp = new File(command.getDir());
            Process process = Runtime.getRuntime().exec(command.getDir(), command.getEnvp(), dirTmp);
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = input.readLine()) != null) {
                result.append(line);
                result.append("\n");
            }
            input.close();
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "invoke error!";
        }
    }

如果需要的话只需要关注executeCommand这个方法就可以了

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值