【发布时间】:2013-12-21 08:40:40
【问题描述】:
Process p;
String cmd = "rsync --timeout=20 -v -r -E -e \"ssh -o StrictHostKeyChecking=no -i "
+ "/usr/local/my.pem\""
+ " root@<IP>:/usr/local/test/ /other/test";
try {
p = Runtime.getRuntime().exec(cmd);
System.out.println("going to exec1");
int val = p.waitFor();
}
当我尝试上面的代码时,rsync 不起作用,val = 1。
如果我直接在ternimal 上尝试cmd 值,它工作正常。
代码有什么问题?
编辑
String[] cmd = new String[]{"rsync", "--timeout=20", "-v", "-r", "-a", "-E", "-e",
"\"ssh -o StrictHostKeyChecking=no -i " + "/usr/local/my.pem" + "\"",
"root" + "@" + "198.168.1.3" + ":" + "/usr/local/test1" ,
"/usr/local" + "/" + "test1"};
try {
p = Runtime.getRuntime().exec(cmd);
System.out.println("going to exec1");
int val = p.waitFor();
}
这次val = 12
现在有什么问题
【问题讨论】:
-
奥古斯托是对的。还要记住 javas Runtime.exec 不会插入 shell 元字符。
-
删除您在 ssh 命令周围添加的
\"字符。您只需要在 shell 命令行上使用引号来告诉 shell 单词边界在哪里,使用多参数exec您已经自己完成了单词拆分。正如现在所写的那样,您告诉 rsync 使用名为 doublequote-s-s-h 的命令,该命令不存在。