Runtime.getRuntime().exec to pass parameter when prompted

喜欢而已 提交于 2019-12-12 12:04:08

问题


I am using the below java statement to start the PostgreSQL server from java code. I am using Runtime.getRuntime().exec() method to achieve this.

 final Process startServer = Runtime.getRuntime().exec("PostgreQL -D data/dir/ start");

Here when the server is SSL enabled and if the key is password protected, in command line it prompts for password (see below lines). In this case how can I pass the password.

Is server running?
starting server anyway
waiting for server to start......Enter PEM pass phrase:....

Do we have any option to pass the password as a parameter, when prompted ? or in PostgreSQL while starting do we have any provision to pass the keypassword (like - " PostgreSQL -d data/dir/ -keyPass password start") ?

Please help me out. Any help or suggestion will be really appreciated. Thanks in advance.


回答1:


You can open the OutputStream of the process and pass the passphrase which will be read by the server as if you typed it is coming from STDIN.

final Process startServer = Runtime.getRuntime().exec("PostgreQL -D data/dir/ start");
PrintStream ps = new PrintStream(startServer.getOutputStream());
ps.println(passPhrase);



回答2:


One alternative to the answer provided above is to create a password file.

(e.g ~/.pgpass file (%APPDATA%\postgresql\pgpass.conf on Windows) formatted as:

hostname:port:database:username:password



回答3:


Start by having a look at ProcessBuilder, it will make you life much easier....

ProcessBuilder pb = new ProcessBuilder("PostgreQL", "-D", "data/dir/" "start");
Process p = pb.start();

InputStream is = p.getInputStream();
OutputStream os = p.getOutputStream();

// Create a separate thread to read the input as needed...
// Create a seperate thread to deal with the output as needed...


来源:https://stackoverflow.com/questions/14639902/runtime-getruntime-exec-to-pass-parameter-when-prompted

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