Java调用bash“;苏-c。。。用户名";出口代码125
我想使用rsync备份文件。 我像这样使用Java调用shellJava调用bash“;苏-c。。。用户名";出口代码125,java,runtime,exec,su,Java,Runtime,Exec,Su,我想使用rsync备份文件。 我像这样使用Java调用shell String cmd = "su -c \"rsync -avrco --progress /opt/tmp /opt/tmp2\" apache"; Process p = Runtime.getRuntime().exec(cmd); 但是p.waitFor()| p.exitValue()是125。 为什么是125 当cmd为“su-cwhoami”时,p.waitFor()| p.exitValue()为0。没关系 完整
String cmd = "su -c \"rsync -avrco --progress /opt/tmp /opt/tmp2\" apache";
Process p = Runtime.getRuntime().exec(cmd);
但是p.waitFor()| p.exitValue()是125。
为什么是125
当cmd为“su-cwhoami”时,p.waitFor()| p.exitValue()为0。没关系
完整的java测试代码是:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws Exception {
String cmd = "su -c \"rsync -avrco --progress /opt/tmp /opt/tmp2\" apache";
// String cmd = "su -c whoami";
Process p = Runtime.getRuntime().exec(cmd);
BufferedInputStream inputStream = new BufferedInputStream(p.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
inputStream.close();
reader.close();
System.out.println(p.waitFor());
System.out.println(p.exitValue());
}
}
顺便说一句,我有办法做到这一点:
1.write cmd to file
2.use Runtime.getRuntime().exec("sh file");
it works well.
问题是您试图执行以下操作:
su-c“rsync-avrco--progress/opt/tmp/opt/tmp2”apache
使用双引号来为su定义一个参数,但双引号是由shell而不是Java理解的(这就是为什么在第二种情况下它可以工作的原因)
要使其工作,请尝试以下方法:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws Exception {
String[] cmd = new String[] {"su", "-c", "rsync -avrco --progress /opt/tmp /opt/tmp2", "apache"};
Process p = Runtime.getRuntime().exec(cmd);
BufferedInputStream inputStream = new BufferedInputStream(p.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
inputStream.close();
reader.close();
System.out.println(p.waitFor());
System.out.println(p.exitValue());
}
}
它起作用了!谢谢大家!
我见过这个方法
public Process exec(String命令,String[]envp)抛出IOException
envp-字符串数组,其中的每个元素都有格式为name=value的环境变量设置,如果子流程应该继承当前流程的环境,则为null<但是当我看到envp是name=value对时,“apache”只是一个值,所以我放弃了