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!";
}
}
【Java调用shell脚本】
文章图片
如果需要的话只需要关注executeCommand这个方法就可以了
推荐阅读
- Linux|109 个实用 shell 脚本
- linux笔记|linux 常用命令汇总(面向面试)
- Linux|Linux--网络基础
- linux|apt update和apt upgrade命令 - 有什么区别()
- linux|2022年云原生趋势
- Go|Docker后端部署详解(Go+Nginx)
- 开源生态|GPL、MIT、Apache...开发者如何选择开源协议(一文讲清根本区别)
- GitHub|7 款可替代 top 命令的工具