[BE/Java] 커맨드 명령어(리눅스/윈도우) 실행 개념 및 샘플소스

2023. 7. 13. 17:39
728x90
반응형

Process

1) 패키지: java.lang.process

2) 명령어를 스트링으로 받아 서버(리눅스.윈도우)에서 실행

 

 

Command

1) 리눅스의 경우 "/bin/sh", "-c" 선입력 필요

2) 명령어는 String 고정배열에 담아 처리

 

 

주의사항

1) cp mv 등의 명령어는 폴더가 미리 생성되어있어야 함

2) 명령어별 허용되는 옵션에 대한 분기처리 필요

 

 

샘플소스

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.ArrayLisy;

public class LinuxCommandExecution {
    public static void main(String[] args) {
        try {
            // 명령어 실행
            String prefix = "/bin/sh";
            String prefix2 = "-c";
            String listAll = "ls -al";

			List<String> cmdList = new ArrayList<>();
            cmdList.add(prefix);
            cmdList.add(prefix2);
            cmdList.add(listAll);
            String[] cmd = cmdList.toArray(new String[cmdList.size()]);

            Process process = Runtime.getRuntime().exec(cmd);

            // 실행 결과 출력
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "EUC-KR"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 에러 출력
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), "EUC-KR"));
            String errorLine;
            while ((errorLine = errorReader.readLine()) != null) {
                System.err.println(errorLine);
            }

            // 프로세스 종료 대기
            int exitCode = process.waitFor();
            System.out.println("Exit Code: " + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

728x90
반응형

BELATED ARTICLES

more