java 셸 스크립트 실행 방법 예시
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 라이브러리나 다른 유사한 자바 라이브러리로 바꾸는 것이 좋습니다. 다음 글에서 어떻게 사용하는지 소개하겠습니다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
git-자동화 스크립트우선 우리는https://github.com/github에서 GitHub 창고를 신청했습니다.(과정은 소개하지 않겠습니다) 이제 우리는git의 자동 스크롤 스크립트를 작성합니다. - 버전 번호를 통해 코드를 스크롤합...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.