如何从Java调用Linux shell命令

9lowa7mx  于 2023-10-23  发布在  Shell
关注(0)|答案(4)|浏览(160)

我尝试使用重定向(>&)和管道(|)。Java如何调用cshbash命令?
我试着用这个:

Process p = Runtime.getRuntime().exec("shell command");

但它与重定向或管道不兼容。

rdrgkggo

rdrgkggo1#

exec不执行shell中的命令
尝试

Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});

而不是.
编辑:我的系统上没有csh,所以我用bash代替。以下为我工作

Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});
20jt8wwn

20jt8wwn2#

使用ProcessBuilder分隔命令和参数,而不是空格。无论使用什么shell,这都应该起作用:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(final String[] args) throws IOException, InterruptedException {
        //Build command 
        List<String> commands = new ArrayList<String>();
        commands.add("/bin/cat");
        //Add arguments
        commands.add("/home/narek/pk.txt");
        System.out.println(commands);

        //Run macro on target
        ProcessBuilder pb = new ProcessBuilder(commands);
        pb.directory(new File("/home/narek"));
        pb.redirectErrorStream(true);
        Process process = pb.start();

        //Read output
        StringBuilder out = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null, previous = null;
        while ((line = br.readLine()) != null)
            if (!line.equals(previous)) {
                previous = line;
                out.append(line).append('\n');
                System.out.println(line);
            }

        //Check result
        if (process.waitFor() == 0) {
            System.out.println("Success!");
            System.exit(0);
        }

        //Abnormal termination: Log command parameters and output and throw ExecutionException
        System.err.println(commands);
        System.err.println(out.toString());
        System.exit(1);
    }
}
aydmsdu9

aydmsdu93#

基于@Tim的例子来创建一个自包含的方法:

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Shell {

    /** Returns null if it failed for some reason.
     */
    public static ArrayList<String> command(final String cmdline,
    final String directory) {
        try {
            Process process = 
                new ProcessBuilder(new String[] {"bash", "-c", cmdline})
                    .redirectErrorStream(true)
                    .directory(new File(directory))
                    .start();

            ArrayList<String> output = new ArrayList<String>();
            BufferedReader br = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
            String line = null;
            while ( (line = br.readLine()) != null )
                output.add(line);

            //There should really be a timeout here.
            if (0 != process.waitFor())
                return null;

            return output;

        } catch (Exception e) {
            //Warning: doing this is no good in high quality applications.
            //Instead, present appropriate error messages to the user.
            //But it's perfectly fine for prototyping.

            return null;
        }
    }

    public static void main(String[] args) {
        test("which bash");

        test("find . -type f -printf '%T@\\\\t%p\\\\n' "
            + "| sort -n | cut -f 2- | "
            + "sed -e 's/ /\\\\\\\\ /g' | xargs ls -halt");

    }

    static void test(String cmdline) {
        ArrayList<String> output = command(cmdline, ".");
        if (null == output)
            System.out.println("\n\n\t\tCOMMAND FAILED: " + cmdline);
        else
            for (String line : output)
                System.out.println(line);

    }
}

(The测试示例是command that lists all files in a directory and its subdirectories, recursively, in chronological order。)
顺便说一句,如果有人能告诉我,为什么我需要4和8个反斜杠,而不是2和4,我可以学到一些东西。还有一个层次的无法逃脱的发生比我计数。
编辑:刚刚在Linux上尝试了同样的代码,结果发现我需要在test命令中使用一半的反斜杠!(也就是:2和4的期望值。)现在它不再只是奇怪,而是一个可移植性问题。

nqwrtyyt

nqwrtyyt4#

你也可以使用我的小库jaxec

import com.yegor256.Jaxec;
String stdout = new Jaxec("shell", "command")
    .withHome("/home/me") // run it in this directory
    .withRedirect(false) // don't redirect STDERR to STDOUT
    .withCheck(false) // ignore the exit code (no exception if it's not zero)
    .exec();

在这里,Jaxec不仅会执行shell命令,还会将其输出发送到Slf4j log,等待其完成,将stderr重定向到stdout,并确保在退出代码不等于零时引发异常。显然,在幕后Jaxec使用Runtime

相关问题