How to hide password in python

I need to hide the password when running the user script in the console (ex: mysql -p ). I use argparse for input parameters, how can I add getpass for param password?

 parser = argparse.ArgumentParser() parser.add_argument('-p', action='store', dest='password', type=getpass.getpass()) 

When I ran script: python script.py -u User -p I get a separate line for entering a password ( Password: , but after raising raise Exception: ValueError: 'my_password' is not callable

+6
source share
3 answers

This guy should solve your problem: getpass

Here is an example with a custom action

 class PwdAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): mypass = getpass.getpass() setattr(namespace, self.dest, mypass) parser = argparse.ArgumentParser() parser.add_argument('-f', action=PwdAction, nargs=0) 
+5
source

EDIT: My previous answer was incorrect and based on an assumption. It was my attempt at a working solution. @qwattash answered correctly correctly, but since I spent ten minutes on this, I decided that I would correct my answer.

 import argparse import getpass class Password(argparse.Action): def __call__(self, parser, namespace, values, option_string): if values is None: values = getpass.getpass() setattr(namespace, self.dest, values) parser = argparse.ArgumentParser() parser.add_argument('-p', action=Password, nargs='?', dest='password') args = parser.parse_args() password = args.password #either from command line or from prompt 
+3
source

Short answer: No, you cannot!

argparse module does not intend to do this. You must request a password in another separate process. In addition, the type argument is just a value converter used before storing the value.

-1
source

Source: https://habr.com/ru/post/986237/


All Articles