进程运行时传递输入

我有rsync命令在java程序中运行…我面临的问题是rsync需要输入密码,我不知道如何将此密码传递给rsync命令工作?

我要发布这段代码示例:

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

但是Vineet Reynolds领先于我。

正如Vineet Reynolds指出的那样,使用这种方法需要一段额外的代码来检测rsync何时需要密码。 所以使用外部密码文件似乎是一种更简单的方法。

PS:可能存在与编码有关的问题,可以通过使用如此处所述的适当编码将字符串转换为字节数组来解决。

PPS:似乎我还没有评论答案,所以我不得不发布一个新答案。

您可以写入Process的输出流,以传入任何输入。 但是,这将要求您了解rsync的行为,因为只有在检测到密码提示时(通过读取Process的输入流),您才必须将密码写入输出流。

但是,您可以创建一个非世界可读的密码文件,并在从Java启动rsync进程时使用--password-file选项传递此密码文件的位置。

花了我一些时间,但在这里:

  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 (); 

PS:我真的不知道rsync是如何工作的,所以你可能需要稍微改一下 – 只需从终端手动运行rsync,看看它究竟是如何请求密码的。

不必等到请求密码将其写入流。 请改用BufferedWriter。

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

这必须奏效。