Example of a shell script method to run in Java

  • 2020-04-01 02:36:24
  • OfStack


The command can now be executed through the commandhelper.execute method, which is implemented by this class


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

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) {
}
}
        }
    }
}

The CommandHelper class USES the CommandResult object to output a result error message. This class to implement


package javaapplication3;

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;
    
    public String getError() {
        return error;
    }
    
    public void setError(String error) {
        this.error = error;
    }
}

Now look at a demonstration of the calling code (the main function takes a timeout parameter) :


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());
        }
    }

The result is a testdir directory.
I tried to create using this method to SSH into the remote machine and encountered two problems:
1) if you want to have no man-machine conversation mode, you need to use the command sshpass-p password SSH user@targetip 'command'.
2) it is not possible to run the project directly on NetBeans because the permissions are not sufficient and you need to run the Java Java application3.main on the terminal
3) many commands cannot be run, only commands such as PWD can be run, the reason is not clear, it is better to use Ganymed ssh-2 library or other similar Java library, I will introduce how to use in the next article.


Related articles: