Search code examples
pythonshellgetpass

Making getpass read from shell script


I have python script (3rd party script) calling getpass.
I need to use a script to provide the password. Simple piping doesn't work because getpass, according to the doc, reads from /dev/tty.
I'm by no means a shell or python expert, so is there a way (without modifying the .py script that uses getpass) to provide the password via bash\shell script?


Solution

  • This is basically designed to get input from the keyboard. If you don't want that, and you can't change the script to read it from a correctly-permissioned configuration file instead, then I would just monkeypatch out the getpass call entirely.

    from mock import patch
    
    with patch('path.to.import.getpass') as mock:
        mock.return_value = 'hunter2'
        # call your script
    

    To elaborate on "call your script", if this script has a proper entry point, e.g. generated from setuptools, then look in the source to find the underlying function that is called. You may import the module and call the same function directly to "run" the script. However, if the script is just a bunch of module level code, then you'll have to use exec and explicitly pass in a scope including the monkeypatch.