Shell script call contains SSH from java

I am trying to invoke a shell script containing an SSH command from a java program. However, it does not work with error code 1.

My java code looks like this:

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);  
    }
}

I compiled the program and put the executable jar in my Unix environment.

shell script that is called from java

ssh -l >test.log

I used the following command to run my java program:

java -jar invokeScript.jar /tmp/upog/test.sh

output

Inside invoke Script 
The Exit Value 1.

If I have another command in a shell like script ls -al > test.log, the code works successfully and I get a return value of 0.

Also, if I call the shell script containing the ssh command directly in the Unix field, it works fine (the field has a connection without a password)

But it fails if I call from java ...

Any advice ....

+4
2

invokeScript.jar . /tmp/upog/test.sh. , :

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

ssh -l someuser example.com >test.log?

script, 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 )

+5

: 0 >= 1 . . . 1 , , , . - 0 , - , > 0. nix- 0 1.

ls -al > test.log

, 0 + 0 - 0.

ssh -l >test.log

"ssh -l" , . , " > test.log" , 1.

, , .

. ssh -l >test.log 2>&1 test.log .

-

BufferedReader err = new BufferedReader( new InputStreamReader(p.getErrorStream()) ); //   java . : java- ,

: 2.&12>&1

+1

Source: https://habr.com/ru/post/1525960/


All Articles