I have a Java program that is running shell commands. Everything works fine, with me being able to see if the commands work or have an error... except for when the commands have a prompt for the user to enter more information.
For example when I run the command ssh-keygen -t rsa -b 4096 -f my_key_name
, the program will just spin forever and not return to the user, since it is waiting for me to enter the password. Now I know I could put in -P ""
to skip me adding a password, but my issue is with other commands that prompt for information.
I just want to know how I could return the prompt text to the user (as I don't really need the ability for the user to enter in their response to the prompt).
RunCommandDto runCommandDto = new RunCommandDto();
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec('ssh-keygen -t rsa -b 4096 -f my_key_name');
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String output = "";
while ((String sInOut = stdInput.readLine()) != null) {
output += sInOut + "\n";
}
while ((String sErr = stdError.readLine()) != null) {
output += sErr + "\n";
}
答案 0 :(得分:0)
The stdin of the exec'd process can be accessed through proc.getOutputStream()
Everything you send through this stream will be delivered to the ssh-keygen process through its stdin.
Of course, if you don't send the kind of input it's expecting, the process may just return some warning message and keep on waiting. What you need to send will be very dependent on the process you're sending it to.
Also: You're processing ssh-keygen's output by reading the InputStream and Error Stream. However, you'll likely want to do this in a separate thread - the way you have it now, if the process writes too much to stderr before writing to stdout, it may hang because of a full buffer...