Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine commons-cli and password prompt in Java

I'm currently using import org.apache.commons.cli

Let's say I have a command line parser like:

private static commandLineParser(Options options, String[] strings) throws ParseException {
    options.addOption("u", "username", true, "Login Username");
    options.addOption("p", "password", true, "Login Password");
    // Some other options
    CommandLineParser parser = new DefaultParser();
    return parser.parse(options, strings);
}

and my main function:

public static void main(String args[]) {
    Options options = new Options();
    CommandLine cmd = null;
    try {
        cmd = commandLineParser(options, args);
        //some helpFormatter stuff to make the options human-readable
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(2);
    }
    //calling my main program
    doSomething(cmd)
}

For obvious reasons I want to omit the password from the command line, since it would be visible in both the history and the process list. However my main program expects an object of type CommandLine. Is there any way to parse a password with a similar behaviour as console.readPassword() or even call this function and add it to the CommandLine object?

I've already tried to search for a combination of commons-cli and password parsing but was not successful.

like image 386
Thanathan Avatar asked Feb 25 '26 12:02

Thanathan


1 Answers

While there doesn't seem to be a way in commons-cli to add an option value to the CommandLine object, you can (hopefully) modify your doSomething(cmd) program to read from stdin.

If the password was provided on the commandline, accept it. If not, read from stdin on the fly.

For example:

private void doSomething(CommandLine cmd) {
    String username = cmd.getOptionValue("username");
    char[] password = (cmd.hasOption("password"))
                ? cmd.getOptionValue("password").toCharArray()
                : System.console().readPassword("Enter password for %s user: ", username);
}
like image 85
jewbix.cube Avatar answered Feb 28 '26 03:02

jewbix.cube



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!