【发布时间】:2014-03-06 05:10:00
【问题描述】:
我正在尝试从 java 程序调用包含 SSH 命令的 shell 脚本。但是它失败了,错误代码为 1。
我的java代码如下:
public class CallScript {
private static String filePath="";
private static String args1="";
public static void main(String[] args) throws Exception{
if(args!=null && args.length > 0){
filePath = args[0];
if(args.length > 1){
args1=args[1];
}
}else{
throw new Exception("File Path should be first Argument");
}
System.out.println(args.length);
invokeScript(filePath,args1);
}
private static void invokeScript(String filePath, String arg1) throws Exception{
System.out.println("Inside invoke Script " + arg1);
Process p = Runtime.getRuntime().exec(filePath);
p.waitFor();
int exitVal = p.exitValue();
System.out.println("The Exit Value " + exitVal);
}
}
我编译了程序并将可执行的 jar 放在我的 Unix 环境中。
从 java 调用的 shell 脚本
ssh -l >test.log
我使用以下命令来运行我的 java 程序:
java -jar invokeScript.jar /tmp/upog/test.sh
输出
Inside invoke Script
The Exit Value 1.
如果我在 shell 脚本中有一些其他命令,例如 ls -al > test.log,则代码运行成功,我得到的返回值为 0。
另外,如果我直接在 Unix 盒子中调用包含 ssh 命令的 shell 脚本,它工作正常。(盒子有无密码连接)
但是如果我从 java 调用它会失败...
任何建议....
【问题讨论】:
-
'filePath' 的值是多少?
-
filePath 将保存 args[0] ,即 /tmp/upog/test.sh
-
我相信你想做
Runtime.getRuntime().exec(arg1);而不是Runtime.getRuntime().exec(filePath); -
我想执行shell脚本,它存在于'filePath'中,目前没有使用args1