Java调用shell脚本

Bertha 。 2023-03-01 09:48 29阅读 0赞
  1. public class ShellTest {
  2. private String callScript( String... workspace) {
  3. try {
  4. File dir = null;
  5. if (workspace[0] != null) {
  6. dir = new File(workspace[0]);
  7. System.out.println(workspace[0]);
  8. }
  9. // String[] evnp = {"val=2", "call=Bash Shell"};
  10. Process process = Runtime.getRuntime().exec("./invokeJ.sh", null, dir);
  11. BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
  12. StringBuilder result = new StringBuilder();
  13. String line;
  14. while ((line = input.readLine()) != null) {
  15. result.append(line);
  16. result.append("\n");
  17. }
  18. input.close();
  19. return result.toString();
  20. } catch (Exception e) {
  21. e.printStackTrace();
  22. return "invoke error!";
  23. }
  24. }
  25. public static void main(String[] args) {
  26. // TODO Auto-generated method stub
  27. ShellTest call = new ShellTest();
  28. System.err.println(call.callScript("/export/data/shell"));
  29. }
  30. }

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

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0lCTGlwbHVz_size_16_color_FFFFFF_t_70

执行结果:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0lCTGlwbHVz_size_16_color_FFFFFF_t_70 1

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

  1. private void invokeCommand(final HttpExchange httpExchange) {
  2. logger.info("invoke command service start!");
  3. String requestBody = IOUtil.readStream(httpExchange.getRequestBody());
  4. CommandDefinition command = JSON.parseObject(requestBody, CommandDefinition.class);
  5. Assert.checkNonNull(command);
  6. Assert.check(StringUtils.isBlank(command.getCommand()), "command is null");
  7. Assert.check(StringUtils.isBlank(command.getDir()), "dir is null");
  8. logger.info("invoke command request body:{}", JSONObject.toJSONString(command));
  9. String result = executeCommand(command);
  10. logger.info("invoke command result:{}", result);
  11. }
  12. private String executeCommand(CommandDefinition command) {
  13. try {
  14. File dirTmp = new File(command.getDir());
  15. Process process = Runtime.getRuntime().exec(command.getDir(), command.getEnvp(), dirTmp);
  16. BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
  17. StringBuilder result = new StringBuilder();
  18. String line;
  19. while ((line = input.readLine()) != null) {
  20. result.append(line);
  21. result.append("\n");
  22. }
  23. input.close();
  24. return result.toString();
  25. } catch (Exception e) {
  26. e.printStackTrace();
  27. return "invoke error!";
  28. }
  29. }

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0lCTGlwbHVz_size_16_color_FFFFFF_t_70 2

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

发表评论

表情:
评论列表 (有 0 条评论,29人围观)

还没有评论,来说两句吧...

相关阅读