How to handle reading java passwd when System.console () returns null?

I am writing a command line program that asks for a password, and I do not want it to execute a local echo of password characters. After some searching, I came across System.console().readPassword() , which seems great, except when it comes to pipes on Unix. So, my sample program (below) works fine when I call it like:

 % java PasswdPrompt 

but with Console == null error when I call it like

 % java PasswdPrompt | less 

or

 % java PasswdPrompt < inputfile 

IMHO, this seems like a JVM problem, but I can't be the only one that has run into this problem, so I have to imagine that there are some simple solutions.

Any?

Thank you in advance

 import java.io.Console; public class PasswdPrompt { public static void main(String args[]) { Console cons = System.console(); if (cons == null) { System.err.println("Got null from System.console()!; exiting..."); System.exit(1); } char passwd[] = cons.readPassword("Password: "); if (passwd == null) { System.err.println("Got null from Console.readPassword()!; exiting..."); System.exit(1); } System.err.println("Successfully got passwd."); } } 
+4
source share
2 answers

On the documentation page:

If System.console returns NULL, then Console operations are not allowed, either because the OS does not support them or because the program was run in a non-interactive environment.

The problem is most likely due to the fact that the use of the channel leaves the "interactive" mode, and the use of the input file uses it as System.in , therefore no Console .

** UPDATE **

Here is a quick fix. Add these lines at the end of your main method:

 if (args.length > 0) { PrintStream out = null; try { out = new PrintStream(new FileOutputStream(args[0])); out.print(passwd); out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) out.close(); } } 

And call your application like

 $ java PasswdPrompt .out.tmp; less .out.tmp; rm .out.tmp 

However, your requested password will be in a text file (albeit hidden) until the command completes.

0
source

So, for some reason, when System.console () returns null, the terminal echo is always turned off, so my problem becomes trivial. The following code works exactly as I wanted. Thanks for the help.

 import java.io.*; public class PasswdPrompt { public static void main(String args[]) throws IOException{ Console cons = System.console(); char passwd[]; if (cons == null) { // default to stderr; does NOT echo characters... not sure why System.err.print("Password: "); BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); passwd= reader.readLine().toCharArray(); } else { passwd = cons.readPassword("Password: "); } System.err.println("Successfully got passwd.: " + String.valueOf(passwd)); } } 
0
source

Source: https://habr.com/ru/post/1343927/


All Articles