调用shell脚本包含来自java的SSH
发布时间:2020-12-15 21:34:17 所属栏目:安全 来源:网络整理
导读:我试图从 java程序调用包含SSH命令的shell脚本.但是它失败了,错误代码为1. 我的java代码如下: public class CallScript { private static String filePath=""; private static String args1=""; public static void main(String[] args) throws Exception{
我试图从
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作为我实际服务器的替换文本) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |