在java

时间:2017-12-04 15:24:19

标签: java linux shell

Java中,您可以调用这样的shell文件:

public class Shell {
    private static Shell rootShell = null;
    private final Process proc;
    private final OutputStreamWriter writer;

    private Shell(String cmd) throws IOException {
        this.proc = new ProcessBuilder(cmd).redirectErrorStream(true).start();
        this.writer = new OutputStreamWriter(this.proc.getOutputStream(), "UTF-8");
    }

    public void cmd(String command)  {
        try {
            writer.write(command+'\n');
            writer.flush();
        } catch (IOException e) {   }
    }

    public void close() {
        try {
            if (writer != null) {  
                writer.close();
                if(proc != null) {  
                    proc.destroy();
                }
            }
        } catch (IOException ignore) {}
    }

    public static void exec(String command) {
        Shell.get().cmd(command);   
    }

    public static Shell get() {
        if (Shell.rootShell == null) {
            while (Shell.rootShell == null) {
                try {   
                    Shell.rootShell = new Shell("su"); //Open with Root Privileges 
                } catch (IOException e) {   }
            }
        } 
        return Shell.rootShell;
    }
}

Shell.exec("echo " + bt.getLevel() + " > "+ flashfile);     

右。
但我有一个shell,在执行它之后给出一个参数 我怎么能通过这个论点?我不希望用户输入任何内容来运行此shell文件。换句话说,我想完全自动化shell文件。

2 个答案:

答案 0 :(得分:2)

如果要使用Java程序自动化shell文件,可以这样做。您甚至可以将一系列命令传送到保存在文件中的程序,并将其作为批处理执行。

您可以执行以下命令批量命令:

java -cp experiments-1.0-SNAPSHOT.jar ConsoleReader < commands.txt

commands.txt 是一个包含一系列命令的文件:

cmd /k date
cmd /k dir
netstat
ipconfig

或者您可以使用相同的程序允许用户在命令行上执行命令。

您可以在下面找到一个可以编译并以上述方式运行的示例程序。

它做什么?

  1. 它将java.util.Scanner挂钩到控制台输入并消耗每一行。
  2. 然后它产生两个线程,它们监听错误并输入流并写出stderrstdin
  3. 控制台上的空行被忽略
  4. 如果您输入&#34;请阅读&#34;它将执行该文件上的命令。
  5. 来源:

    public class ConsoleReader {
    
        public static void main(String[] args) throws IOException, DatatypeConfigurationException {
            try(Scanner scanner = new Scanner(new BufferedInputStream(System.in), "UTF-8")) {
                readFromScanner(scanner);
            }
        }
    
        private static final Pattern FILE_INPUT_PAT = Pattern.compile("read\\s*([^\\s]+)");
    
        private static void readFromScanner(Scanner scanner) {
            while (scanner.hasNextLine()) {
                try {
                    String command = scanner.nextLine();
                    if(command != null && !command.trim().isEmpty()) {
                        command = command.trim();
                        if("exit".equals(command)) {
                            break; // exit shell
                        }
                        else if(command.startsWith("read")) { // read from file whilst in the shell.
                            readFile(command);
                        }
                        else {
                            Process p = Runtime.getRuntime().exec(command);
                            Thread stdout = readFromStream(p.getInputStream(), System.out, "in");
                            Thread stderr = readFromStream(p.getErrorStream(), System.err, "err");
                            stdout.join(200);
                            stderr.join(200);
                        }
                    }
                }
                catch(Exception e) {
                    Logger.getLogger("ConsoleReader").log(Level.SEVERE, String.format("Failed to execute command %s", e));
                }
            }
        }
    
        private static void readFile(String command) throws FileNotFoundException {
            Matcher m = FILE_INPUT_PAT.matcher(command);
            if(m.matches()) {
                String file = m.group(1);
                File f = new File(file);
                if (f.exists()) {
                    try (Scanner subScanner = new Scanner(f)) {
                        readFromScanner(subScanner);
                    }
                }
            }
            else {
                System.err.printf("Oops, could not find '%s'%n", command);
            }
        }
    
        private static Thread readFromStream(InputStream stdin, PrintStream out, String name) throws IOException {
            Thread thread = new Thread(() -> {
                try (BufferedReader in = new BufferedReader(new InputStreamReader(stdin))) {
                    String line;
                    while ((line = in.readLine()) != null) {
                        out.println(line);
                    }
                } catch (IOException e) {
                    Logger.getLogger("ConsoleReader").log(Level.SEVERE, "Failed to read from stream.", e);
                }
            }, name);
            thread.setDaemon(true);
            thread.start();
            return thread;
        }
    }
    

答案 1 :(得分:1)

Runtime.getRuntime().exec("src/[FILE LOCATION]");

我认为这是你正在寻找的命令。让我知道它是否有效!