Other

java (Spring)로 Shell Script 실행 하기

채마스 2022. 2. 28. 19:54

shell scrip 작성

    //결로  /tmp/sh_aaaa_7010.sh
    echo "test shell scrip!!"
    //결로  /tmp/sh_test_9010.sh
    echo "test shell scrip!!"
    //결로  /tmp/sh_xxxx_9010.sh
    echo "test shell scrip!!"
  • tmp 디렉토리 하위에 3개의 shell scrip 파일을 생성한다.



파일 접근 권한 설정

  • sudo chmod 777 /tmp : tmp 디렉토리에 대한 r: 읽기권한, w: 쓰기권한 x: 실행권한 부여
  • sudo chmod a+x sh_aaaa_7010.sh
  • sudo chmod a+x sh_test_9010.sh
  • sudo chmod a+x sh_xxxx_9010.sh
  • 위와 같이 세개의 shell script 의 권한을 열어둔다.
  • 아래와 같이 권한이 부여된 것을 확인 할 수 있다.




ShellController 작성, yml 작성

@RestController
@RequestMapping("/shell")
@Slf4j
public class ShellController {

    private final static  String PATH = "/tmp/";

    @Value("${shell.s1}")
    private String s1_fileNm;

    @Value("${shell.s2}")
    private String s2_fileNm;

    @Value("${shell.a1}")
    private String a1_fileNm;


    @GetMapping("/exec")
    public void execShell(@RequestParam String param){

        log.info("param : {}", param);
        String fileNm = param;

        switch (param){
            case "s1" : fileNm = s1_fileNm; break;
            case "s2" : fileNm = s2_fileNm; break;
            case "a1" : fileNm = a1_fileNm; break;
        }

        ProcessBuilder pb = new ProcessBuilder(PATH + fileNm);

        try {
            // Run script
            Process process = pb.start();

            // Read output
            StringBuilder output = new StringBuilder();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line);
            }

            System.out.println(output.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
shell:
  s1:
    sh_aaaa_7010.sh
  s2:
    sh_test_9010.sh
  a1:
    sh_xxxx_9010.sh
  • 위와 같이 yml 에 shell script 파일명을 매핑시켜 뒀다.
  • 컨트롤러에서 파라미터로 yml 에 매핑되는 파일이 실행된다.



테스트

  • linux 환경에서 테스트하기 위해 ec2 개인 개정을 사용했다.
  • 아래와 같이 파라미터로 "s1" 을 넘겨서 api 를 보냈다.

  • 아래와 같이 s1 에 매핑되는 sh_aaaa_7010.sh 이 실행된 것을 확인할 수 있다.




REFERENCES