Process Runtime pass input

后端 未结 4 890
执笔经年
执笔经年 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: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.

提交回复
热议问题