3

我目前正在使用import org.apache.commons.cli

假设我有一个命令行解析器,例如:

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);
}

和我的主要功能:

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)
}

出于显而易见的原因,我想从命令行省略密码,因为它在历史记录和进程列表中都可见。但是我的主程序需要一个命令行类型的对象。有什么方法可以解析具有类似行为的密码,console.readPassword()甚至调用此函数并将其添加到 CommandLine 对象?

我已经尝试搜索 commons-cli 和密码解析的组合,但没有成功。

4

1 回答 1

2

虽然在 commons-cli 中似乎没有办法向CommandLine对象添加选项值,但您可以(希望)修改您的doSomething(cmd)程序以从标准输入读取。

如果在命令行上提供了密码,请接受它。如果没有,请即时从标准输入读取。

例如:

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);
}
于 2018-03-17T21:02:04.763 回答