0

Assume this code as a simple Python code which can get username and password:

from getpass import getpass

user = getpass(" enter username :")
pass = getpass(" enter password ")
print("user = ", user)
print("pass = ", pass)

in addition, suppose that we have a file named input which contains:

myusername

mypassword

I want to send this file as input for the python code in bash:

but this instruction doesn't work:

python3 get_user_pass.py < input

this is because of using getpass function, and if we use input instead of getpass, it will work correctly. How we can send an input file from bash to our python code which uses getpass?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Saeed
  • 159
  • 3
  • 13

2 Answers2

0

getpass() reads form /dev/tty and by definition requires an interactive shell. It will not read input from stdin (or any file for that matter).

The getpass function is used for hiding the input echo. Redirecting a file stream to the input does not display echo anyhow.

Yotamz
  • 173
  • 4
  • 1
    so it means there isn't any way in order to send input data from bash to python code? – Saeed Dec 01 '19 at 09:36
  • The getpass function is built not to read from there. Since the file redirect does not display the contents on the terminal, it is effectively "hidden", which is the only reason to use getpass to begin with. – Yotamz Dec 01 '19 at 09:44
  • @Saeed IIRC using gdb you can redirect the file descriptor pointing to /dev/tty to another file while python is waiting for input. It's too much work though – oguz ismail Dec 01 '19 at 10:12
0

We pass the file name as an argument while executing the script. The script will open the passed filename and read for the contents line by line and refer to the content as a list.

User and Password file:

bash-3.2$ cat /Users/anku/Documents/project/config.txt
user_xyz
user_xyz_pass
bash-3.2$ 

Python script:

#!/usr/bin/python
import sys

file_name = str(sys.argv[1])
print (file_name)

file = open(file_name, 'r')
content = file.read()
paths = content.split("\n")
user = str(paths[0])
password = str(paths[1])
print("user = ", user)
print("pass = ", password)

Execute Python Script:

bash-3.2$ python /Users/anku/Documents/project/usr_pass.py /Users/anku/Documents/project/config.txt
/Users/anku/Documents/project/config.txt
user =  user_xyz
pass =  user_xyz_pass
bash-3.2$ 

Hope this helps. Good Luck !!

Piyush
  • 818
  • 8
  • 17
  • Actually this is not the thing that I want, my program needs to use getpass and shouldn't use input parameters from file. – Saeed Dec 01 '19 at 11:49