Process Runtime pass input

后端 未结 4 870
执笔经年
执笔经年 2021-01-03 15:02

I have rsync command to be run in a java program...the problem i am facing is that rsync requires a password to be entered and i am not understanding how to pass this passwo

相关标签:
4条回答
  • 2021-01-03 15:23

    You can write to the output stream of the Process, to pass in any inputs. However, this will require you to have knowledge of rsync's behavior, for you must write the password to the outputstream only when the password prompt is detected (by reading the input stream of the Process).

    You may however, create a non-world readable password file, and pass the location of this password file using the --password-file option when you launch the rsync process from Java.

    0 讨论(0)
  • 2021-01-03 15:24

    Took me some time, but here it goes:

        Process ssh = Runtime.getRuntime ().exec (new String[] {"rsync", ... /*other arguments*/});
        Reader stdOut = new InputStreamReader (ssh.getInputStream (), "US-ASCII");
        OutputStream stdIn = ssh.getOutputStream ();
    
        char[] passRequest = new char[128];//Choose it big enough for rsync password request and all that goes before it
        int len = 0;
        while (true)
        {
            len += stdOut.read (passRequest, len, passRequest.length - len);
            if (new String (passRequest, 0, len).contains ("password:")) break;
        }
    
        System.out.println ("Password requested");
        stdIn.write ("your_password\n".getBytes ("US-ASCII"));
        stdIn.flush ();
    

    P.S.: I don't really know how rsync works, so you may need to change it a bit - just run rsync manually from a terminal an see how exactly it requests a password.

    0 讨论(0)
  • 2021-01-03 15:30

    Need not wait till the password is requested to write it to the stream. Make use of a BufferedWriter instead.

    BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(process.getOutputStream())
    );
    writer.write(passwd, 0, passwd.length());
    writer.newLine();
    writer.close();
    

    This must work.

    0 讨论(0)
  • 2021-01-03 15:46

    I was gonna post this code sample:

    Process rsyncProc = Runtime.exec ("rsync");
    OutputStreanm rsyncStdIn = rsyncProv.getOutputStream ();
    rsyncStdIn.write ("password".getBytes ());
    

    But Vineet Reynolds was ahead of me.

    As Vineet Reynolds pointed out using such approach will require an additional piece of code to detect when rsync requires a password. So using an external password file seems to be an easier way.

    P.S.: There may be a problem related to the encoding, it can by solved by converting the string to a byte array using appropriate encoding as described here.

    P.P.S.: It seems that I can't yet comment an answer, so I had to post a new one.

    0 讨论(0)
提交回复
热议问题