温馨提示×

SpringBoot CommandLine与Shell脚本如何交互

小樊
95
2024-07-13 19:02:28
栏目: 编程语言

要在SpringBoot应用中与Shell脚本交互,可以使用Java中的ProcessBuilder类来执行Shell命令,并通过标准输入输出流来与Shell脚本交互。

以下是一个简单的示例代码,演示了如何在SpringBoot应用中执行Shell脚本并与其交互:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ShellController {

    @GetMapping("/executeShell")
    public String executeShell() {
        try {
            ProcessBuilder pb = new ProcessBuilder("/path/to/your/shell/script.sh");
            Process process = pb.start();

            // 读取Shell脚本的输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 向Shell脚本输入参数
            process.getOutputStream().write("input parameters\n".getBytes());
            process.getOutputStream().flush();

            // 等待Shell脚本执行结束
            int exitCode = process.waitFor();
            System.out.println("Shell脚本执行完毕,退出码为:" + exitCode);

            return "Shell脚本执行完毕,退出码为:" + exitCode;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return "执行Shell脚本出错:" + e.getMessage();
        }
    }
}

在这个示例中,我们通过ProcessBuilder类创建一个新的进程来执行Shell脚本,并通过标准输入输出流与Shell脚本交互。在Shell脚本执行完毕后,我们可以获取其退出码来判断执行结果。

请注意,要确保在SpringBoot应用中执行Shell脚本时,应注意安全性和权限控制,避免造成潜在的安全风险。

0