Question

I am looking for a way to prompt for password (that is, no input echo). I am using jython in WebSphere's 7.0.0.19 wsadmin.

I've looked for it - it appears to be possible with import getpass or import termios (but I get "no module named ..." exception).

Any way to prompt for password anyway?

Thank you.

Était-ce utile?

La solution

You can use the following code. It basically uses Java's console() if present (note that console may not be present all the time) else use raw_input() and password masking logic.

# if console is not available (ex: when invoked from a shell script or another java process)
# we need to fall back to use raw_input, but we should mask the password if we use it
import sys, thread, time, threading
from java.lang import String
def getPass(stream=None):
    console = java.lang.System.console()
    if console is None:
        global p_stopMasking
        if not stream:
            stream = sys.stderr
        try:
            p_stopMasking = 0
            threading.Thread(target=_doMasking,args=(stream,)).start()
            password = raw_input()
            p_stopMasking = 1
        except Exception, e:
            p_stopMasking = 1
            print "Error Occured"
            print e
            exit()
    else:
        password = console.readPassword()
    return String.valueOf(password)

def _doMasking(stream):
    while not p_stopMasking:
        stream.write("\010*")
        #stream.write("\n")
        stream.flush()
        time.sleep(0.01)

def populateCredentials():
    global username
    global password
    print 'Enter username:'
    username = raw_input();
    print 'Enter password:'
    password = getPass(sys.stdout);

# start main
print 'start program...'
p_stopMasking= 1
username     = None
password     = None
populateCredentials()
print 'username is : ' + username
print 'password is  : ' + password

Autres conseils

The following also worked for me:

raw_input("")
myPass = raw_input("Please enter a password: ")

This isn't perfect because it doesn't mask the password, but it does work. For some reason, if you don't specify the first "raw_input" invocation then the script won't block on the second one.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top