微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

调用shell脚本包含来自java的SSH

我试图从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调用

任何建议….

解决方法:

invokeScript.jar在这里对我很好.问题似乎与/tmp/upog/test.sh有关.如果我尝试运行命令,我得到:

$ssh -l >test.log
ssh: option requires an argument -- l
[...]

你的意思是ssh -l someuser example.com> test.log?

当我使用无错误的shell脚本测试它时,运行ssh工作:

$cat >/tmp/upog/test.sh
#!/bin/bash
ssh example.com ls /tmp/upog >test.log
$chmod +x /tmp/upog/test.sh
$java -jar invokeScript.jar /tmp/upog/test.sh 
1
Inside invoke Script 
The Exit Value 0
$cat test.log
bar
baz
foo

(使用example.com作为我实际服务器的替换文本)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐