Python: using getpass with argparse

I looked around, but found nothing.

Basically I was wondering if it can be used getpass.getpass()with argparse.

At the moment, I have the following as a job, I'm just wondering if there is a better way:

import argparse
import getpass

parser = argparse.ArgumentParser(description="Some description")
parser.add_argument('-p', metavar="password", default="foobarblah123", help="password for user (default to prompt user)")
...
parsed_args = parser.parse_args()
args = vars(parsed_args)
user_pass = args['p']
if user_pass == "foobarblah123":
  user_pass = getpass.getpass()

I'm sure this is not the best way to handle this, however there is a requirement to have a command line parameter for the password ... best practice or not.

Thank.

+7
source share
4 answers

I think I could find a better way to do this. How about using a special action like this:

import argparse
import getpass

class PasswordPromptAction(argparse.Action):
    def __init__(self,
             option_strings,
             dest=None,
             nargs=0,
             default=None,
             required=False,
             type=None,
             metavar=None,
             help=None):
        super(PasswordPromptAction, self).__init__(
             option_strings=option_strings,
             dest=dest,
             nargs=nargs,
             default=default,
             required=required,
             metavar=metavar,
             type=type,
             help=help)

    def __call__(self, parser, args, values, option_string=None):
        password = getpass.getpass()
        setattr(args, self.dest, password)

parser.add_argument('-u', dest='user', type=str, required=True)
parser.add_argument('-p', dest='password', action=PasswordPromptAction, type=str, required=True)

args = parser.parse_args()
+12
source

Looking around and not finding a sufficient solution. Here is what I came up with.

from argparse import ArgumentParser
from getpass import getpass

def main():
    parser = ArgumentParser(description="arg parser hidden password input.")
    parser.add_argument('-sp', '--secure_password', action='store_true', dest='password', 
                        help='hidden password prompt')
    args=parser.parse_args()

    if args.password:
        password = getpass()

    print(password)

if __name__ == "__main__":
    main()

, print(password), , , .

+5

, ( Python 3):

import argparse
import getpass


class Password:

    DEFAULT = 'Prompt if not specified'

    def __init__(self, value):
        if value == self.DEFAULT:
            value = getpass.getpass('LDAP Password: ')
        self.value = value

    def __str__(self):
        return self.value


parser = argparse.ArgumentParser(
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-u', '--username', help='Specify username',
    default=getpass.getuser())
parser.add_argument('-p', '--password', type=Password, help='Specify password',
    default=Password.DEFAULT)
args = parser.parse_args()

print(args.username, args.password)

:

$ python ~/Desktop/example.py -h
usage: example.py [-h] [-u USERNAME] [-p PASSWORD]

optional arguments:
  -h, --help            show this help message and exit
  -u USERNAME, --username USERNAME
                        Specify username (default: gavinr)
  -p PASSWORD, --password PASSWORD
                        Specify password (default: Prompt if not specified)

$ python ~/Desktop/example.py -p foo
gavinr foo

$ python ~/Desktop/example.py 
LDAP Password: 
gavinr foo
+3
source

I like this solution because the user can pass both:

$> python program.py login -u user1 -p pass1

or just one:

$> python program.py login -u user1

or any:

$> python program.py login

If no username or password is provided, parameters are requested interactively.

import argparse
import getpass

def parse_args():
    parser = argparse.ArgumentParser(description="command line client")
    subparser = parser.add_subparsers(dest='command', metavar='command')
    subparser.required = True
    parser.set_defaults(funct=argparser_handler)

    # Login
    sub_parser = subparser.add_parser("login", help="Login with email and password")
    sub_parser.add_argument('-u', dest='user', help='user.  If this argument is not passed it will be requested.')
    sub_parser.add_argument('-p', dest='password', help='password.  If this argument is not passed it will be requested.')

    args = parser.parse_args()
    args.funct(args)

def argparser_handler(args):
    if (args.command == 'login'):
        login(args.user, args.password)


def login(user, password):
    if not user:
        user = input("User:") 
    if not password:
        password = getpass.getpass()    
    print("user:", user)
    print("password:", password)


def main():
    pass

if __name__ == '__main__':
    parse_args()
    main()
0
source

All Articles