Java Process streams

安稳与你 提交于 2019-12-08 10:10:38

问题


I have a problem with interacting with some terminal application (in my situation it is openSSL). I have a command to send and then this application wants password and reply given password. My code doesn't work. I mean that I don't see any output from it.

For testing I've made also simple application which is waiting for two strings to type and running it from my Java code works.

Have you any suggestions?

ProcessBuilder pb = new ProcessBuilder("openssl.exe");
    Process process = pb.start();

    final InputStream is = process.getInputStream();
    new Thread(new Runnable() {
        public void run() {
            try {
                BufferedReader reader =
                    new BufferedReader(new InputStreamReader(is));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }).start();


    OutputStream out = process.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));

    writer.write("genrsa -des3 -out ca.key 512\n");
    writer.write("password\n");
    writer.write("password\n");
    writer.flush();

    writer.close();
    process.waitFor();

回答1:


I think, OpenSSL does not behave as you expect. I tried the following (on Linux):

echo $'genrsa -des3 -out xxx.key 512\npassword\npassword\n' \
    | openssl 2>stderr.txt 1>stdout.txt

It prompts me for two password entries on the terminal:

Enter pass phrase for xxx.key:
Verifying - Enter pass phrase for xxx.key:

Stdout.txt receives:

OpenSSL> OpenSSL> OpenSSL> OpenSSL> OpenSSL>

Stderr.txt receives:

Generating RSA private key, 512 bit long modulus
..........++++++++++++
...........++++++++++++
e is 65537 (0x10001)
openssl:Error: 'password' is an invalid command.
openssl:Error: 'password' is an invalid command.

This means that most of openssls output goes to stderr. It does not output newlines to stdout, so that reader.readLine() will never get a complete line. That is why you do not see any output. (Use read() instead. You might also need to read stderr to avoid blocking.)

OpenSSL always tries to get the password from the current terminal without echoing, not from stdin. Presenting them on stdin without special options causes interpretation as commands. For details and options you have see this discussion: Securely passing password to openssl via stdin



来源:https://stackoverflow.com/questions/20033683/java-process-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!