In my current project I am developing some Jython based command line tools and had the need for masking passwords entered in the command shell. Python provides the getpass module for this purpose. Unfortunately this module has not been made available for Jython.
Here comes a module I wrote to provide this kind of functionality. It uses the mechanism described here //java.sun.com/developer/technicalArticles/Security/pwordmask/ to mask characters entered at the command prompt. Additionally if Java 6 or higher is running Jython the module will instead use the new Console.readPassword() method. In case the module is running in an environment where the getpass module is available it will delegate to the corresponding methods of this module instead of using its own implementations.
# ext_getpass.py
# @author Sebastian Thomschke, //sebthom.de/
import thread, sys, time, os
# exposed methods:
__all__ = ["getpass","getuser"]
def __doMasking(stream):
    __doMasking.stop = 0
    while not __doMasking.stop:
        stream.write("b*")
        stream.flush()
        time.sleep(0.01)
def generic_getpass(prompt="Password: ", stream=None):
    if not stream:
        stream = sys.stderr
    prompt = str(prompt)
    if prompt:
        stream.write(prompt)
        stream.flush()
    thread.start_new_thread(__doMasking, (stream,))
    password = raw_input()
    __doMasking.stop = 1
    return password
def generic_getuser():
    for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
        usr = os.environ.get(name)
        if usr: return usr
def java6_getpass(prompt="Password: ", stream=None):
    if not stream:
        stream = sys.stderr
    prompt = str(prompt)
    if prompt:
        stream.write(prompt)
        stream.flush()
    from java.lang import System
    console = System.console()
    if console == None:
	    return generic_getpass(prompt, stream)
    else:
        return "".join(console.readPassword())
try:
    # trying to use Python's getpass implementation
    import getpass
    getpass = getpass.getpass
    getuser = getpass.getuser
except:
    getuser = generic_getuser
	
    # trying to use Java 6's Console.readPassword() implementation
    try:
        from java.io import Console
        getpass = java6_getpass
    except ImportError, e:
        # use the generic getpass implementation
        getpass = generic_getpass
Here is an usage example:
import ext_getpass as getpass
pw = getpass.getpass("Please enter your password:")
print "The entered password was: " + pw
			
With Jython 2.5.1, I get an AttributeError on line 51. Since that block only handles the ImportError, the script was coughing-up a traceback. In my local copy, I’ve changed line 51 to read…
except (ImportError, AttributeError), e: