Wednesday, 1 August 2012

WLST: Password Prompt

It is quite common to need to get a password from a user in a WLST script. Unfortunately WLST does not have the getpass Python package available to it. But WLST is Jython so can make use of the Java JDK classes! Java 6 introduced the Console class that has a readPassword method which would be perfect.

To get a handle on the Console object we get it from the System object:

console = System.console()

We can then invoke the readPassword method. The readPassword method takes as arguments a format string and number of var args. To simplify things we will use a format string that just outputs the first var arg as a string and then pass the prompt in as the first var arg. Jython will interpret the var args as a list so we initialize a list containing the single value which is the prompt :

passwdCharArr = console.readPassword("%s", [prompt])

The final piece of the puzzle is that the readPassword method returns char[]. We want the password as a string value. The Python String object has a join method that will work for this purpose:

passwd = "".join(passwdCharArr)

And that's it. All of this can be truncated into the following:

passwd = "".join(java.lang.System.console().readPassword("%s", [prompt]))

There may be other methods for getting a password, but this works and assuming WLST is invoked from a JDK which is at version 6 (1.6) or greater should be quite portable and not require any other Python packages.