Search code examples
javaruntime.execsshpass

Why runtime.exec() is not executing. when I given sshpass command


Why runtime.exec() is not executing. when I given sshpass command

rt.exec("sshpass -p sbsiz scp '/home/surendra/Desktop/remote_backup.txt' [email protected]:/home/");

but when I Run this command directly in terminal it's working like as in terminal

sshpass -p sbsiz scp '/home/surendra/Desktop/remote_backup.txt' [email protected]:/home/

Solution

  • You can check the Input Stream and Error Stream from the Process class (return for rt.exec) to see what was the actual error due to which the command was not executed like below:

    public static void printStream(InputStream is, String type){
    try
       {
          InputStreamReader isr = new InputStreamReader(is);
          BufferedReader br = new BufferedReader(isr);
          String line=null;
          while ( (line = br.readLine()) != null)
                System.out.println(type + ">" + line);    
       } catch (IOException ioe){
               ioe.printStackTrace();  
       }
    }
    
    public static void main(String args[])
    {
        String cmd = "command to execute";
        Process proc = Runtime.getRuntime().exec("sshpass -p sbsiz scp '/home/surendra/Desktop/remote_backup.txt' [email protected]:/home/");
        printStream(proc.getInputStream(), "OUTPUT");
        printStream(proc.getErrorStream(), "ERROR");
    }