java 셸 스크립트 실행 방법 예시

이제 CommandHelper를 통해.execute 방법은 명령을 실행할 수 있습니다.

package javaapplication3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
 *
 * @author chenshu
 */
public class CommandHelper {
    //default time out, in millseconds
    public static int DEFAULT_TIMEOUT;
    public static final int DEFAULT_INTERVAL = 1000;
    public static long START;
    public static CommandResult exec(String command) throws IOException, InterruptedException {
        Process process = Runtime.getRuntime().exec(command);
        CommandResult commandResult = wait(process);
        if (process != null) {
process.destroy();
        }
        return commandResult;
    }
    private static boolean isOverTime() {
        return System.currentTimeMillis() - START >= DEFAULT_TIMEOUT;
    }
    private static CommandResult wait(Process process) throws InterruptedException, IOException {
        BufferedReader errorStreamReader = null;
        BufferedReader inputStreamReader = null;
        try {
errorStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
inputStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//timeout control
START = System.currentTimeMillis();
boolean isFinished = false;
for (;;) {
if (isOverTime()) {
CommandResult result = new CommandResult();
result.setExitValue(CommandResult.EXIT_VALUE_TIMEOUT);
result.setOutput("Command process timeout");
return result;
}
if (isFinished) {
CommandResult result = new CommandResult();
result.setExitValue(process.waitFor());
//parse error info
if (errorStreamReader.ready()) {
StringBuilder buffer = new StringBuilder();
String line;
while ((line = errorStreamReader.readLine()) != null) {
buffer.append(line);
}
result.setError(buffer.toString());
}
//parse info
if (inputStreamReader.ready()) {
StringBuilder buffer = new StringBuilder();
String line;
while ((line = inputStreamReader.readLine()) != null) {
buffer.append(line);
}
result.setOutput(buffer.toString());
}
return result;
}
try {
isFinished = true;
process.exitValue();
} catch (IllegalThreadStateException e) {
// process hasn't finished yet
isFinished = false;
Thread.sleep(DEFAULT_INTERVAL);
}
}
        } finally {
if (errorStreamReader != null) {
try {
errorStreamReader.close();
} catch (IOException e) {
}
}
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
}
}
        }
    }
}
CommandHelper 클래스에서는 CommandResult 객체 출력 결과 오류 정보를 사용합니다.이런 종류의 실현

package javaapplication3;
/**
 *
 * @author chenshu
 */
public class CommandResult {
    public static final int EXIT_VALUE_TIMEOUT=-1;
    private String output;
    void setOutput(String error) {
        output=error;
    }
    String getOutput(){
        return output;
    }
    int exitValue;
    void setExitValue(int value) {
        exitValue=value;
    }
    int getExitValue(){
        return exitValue;
    }
    private String error;
    /**
     * @return the error
     */
    public String getError() {
        return error;
    }
    /**
     * @param error the error to set
     */
    public void setError(String error) {
        this.error = error;
    }
}

이제 코드를 호출하는 데모를 보십시오. (main 함수는 시간 초과 파라미터를 받아들입니다.)

public static void main(String[] args) {
        try {
int timeout = Integer.parseInt(args[0]);
CommandHelper.DEFAULT_TIMEOUT = timeout;
CommandResult result = CommandHelper.exec("mkdir testdir");
if (result != null) {
System.out.println("Output:" + result.getOutput());
System.out.println("Error:" + result.getError());
}
        } catch (IOException ex) {
System.out.println("IOException:" + ex.getLocalizedMessage());
        } catch (InterruptedException ex) {
System.out.println("InterruptedException:" + ex.getLocalizedMessage());
        }
    }
결과는testdir 디렉터리를 만들 것입니다.나는 이런 방법으로 ssh를 통해 원격 기기에 로그인하는 것을 만들려고 시도했는데 두 가지 문제가 생겼다. 1) 인간 대화 방식이 없으면 명령 sshpass-p password ssh를 사용해야 한다.user@targetIP'command'2) NetBeans에서 프로젝트를 직접 실행해서는 안 됩니다. 권한이 부족하기 때문에 터미널에서 자바 응용 프로그램을 실행해야 합니다.main3) 많은 명령이 실행되지 않고 pwd 등 명령만 실행할 수 있습니다. 원인은 아직 명확하지 않습니다. Ganymed SSH-2 라이브러리나 다른 유사한 자바 라이브러리로 바꾸는 것이 좋습니다. 다음 글에서 어떻게 사용하는지 소개하겠습니다.

좋은 웹페이지 즐겨찾기