0

If I call a external command from a Java program, How can I catch prompt message like the 2nd line below in both windows & linux

>sftp abc@abc.com
sftp>

I already tried below code , but neither InputStream nor ErrorStream can get that prompt message:

private static class PReader extends Thread{
    private final InputStream i;
    private final String label;
    PReader(InputStream i ,String label){
        this.i = i  ;
        this.label = label;
    }
    public void run(){
        int w ;
        int p = 0 ;
        try {
            while((w=i.read())!=-1){
                if(c++ == 0 || '\n' == (char)p) {
                    System.out.print(label);
                }
                System.out.print((char)w);
                p =w ;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
public static void main(String[] args) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder("/usr/bin/sftp",  "abc@abc.com");  
    Process p = pb.start();
    new PReader(p.getInputStream(),"OUT:").start();
    new PReader(p.getErrorStream(),"ERR:").start();
    p.waitFor();
}

Edit: I edited the post so now it's not about asking for password . And I can get that prompt message by redirecting stdout from shell, but still can't get it by java Process

>sftp 1>a.log 2>b.log
>cat a.log
sftp>
Jammy Lee
  • 1,496
  • 1
  • 14
  • 32
  • Programs that ask for passwords usually read/write directly to the console device for the password prompt, for security reasons. They do not use stdin/stdout. – Jim Garrison Nov 29 '17 at 18:10
  • edited the post , now it's not about asking for password – Jammy Lee Nov 29 '17 at 18:33
  • You aren't checking the return status from `waitFor()`. How do you know you successfully launched sftp? – Jim Garrison Nov 29 '17 at 18:36
  • my program hangs on waitFor() ,as it's pending for input, and I can get connected message from stderr , it's something like this "ERR:Connected to xxx.xxx.xxx.xx" – Jammy Lee Nov 29 '17 at 18:37
  • OK. You say Windows but the external command you start has a Linux/Unix path name (`/usr/bin/sftp`). So which is it? Please ensure that you are asking a consistent question. Console interaction is an area where Linux and Windows differ significantly. – Jim Garrison Nov 29 '17 at 18:44
  • **There is no prompt for you to read.** Java `ProcessBuilder` uses pipes for the child process stdin/out/err, and OpenSSH `sftp` does not prompt if its stdin is a pipe -- more exactly it prompts only if `isatty(STDIN)` and batchfile option `-b` is not used and it is not built with `libedit`. To see for yourself do `(sleep 10; echo ls) | sftp user@host | tee stdout` and you will see for 10 seconds it reads with no prompt, then it receives the input command and echoes it with a simulated prompt and executes it. – dave_thompson_085 Nov 30 '17 at 00:53

0 Answers0