开发者

Process Runtime pass input

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 a开发者_C百科m not understanding how to pass this password to the rsync command to work?


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.


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜