The code in question can be rewritten as:
#!/usr/bin/env python3 from pathlib import Path passwords = Path('users.txt').read_text().splitlines() uid = int(input('Your id: \n')) upassword = input('Your password: \n').strip() msg = 'Hello!' if passwords[uid] == upassword else 'Incorrect password.' print(msg)
Although storing cleartext passwords on a disk is not good, even entering a cleartext password is not safe, and it is not very convenient for users to remember their uid .
You can store only the password hash and username instead of asking for the number. For example, to compare a password stored in /etc/passwd using the crypt module :
#!/usr/bin/env python import pwd import crypt import getpass from hmac import compare_digest as compare_hash def login(): username = input('Your user name: ').strip() cryptedpasswd = pwd.getpwnam(username)[1] if cryptedpasswd: if cryptedpasswd == 'x' or cryptedpasswd == '*': raise ValueError('no support for shadow passwords') cleartext = getpass.getpass() return compare_hash(crypt.crypt(cleartext, cryptedpasswd), cryptedpasswd) else: return True # no password
If the password for the desired user is stored in /etc/shadow then you can use spwd.getspnam()[1] to get the password hash and run the script from the user who can read this file (root, shadow group).
To get a password hash:
>>> import crypt >>> crypt.crypt('p4$$wOrd') '$6$NR7pbExWXdzpEti/$3rIzv5vmkvriZie0Hu9Y1n3uCtBdqICn32WCdtfSKzsHFJSBvrPVNhfCuRYX8PwE/gJ8ORW.PurdXlUy1BbGS0'
To save to your file:
>>> hashed_passwd = crypt.crypt('p4$$wOrd') >>> username = 'john' >>> with open('users.txt', 'a') as file: ... file.write(f'{username}:{hashed_passwd}\n')
To read and verify the password:
#!/usr/bin/env python3 import crypt import getpass from hmac import compare_digest as compare_hash from pathlib import Path def login(): username = input('Your user name: ').strip() cryptedpasswd = next((passwd for line in Path('users.txt').read_text().splitlines() for user, passwd in [line.partition(':')[::2]] if user == username), None) if cryptedpasswd is not None: cleartext = getpass.getpass() return compare_hash(crypt.crypt(cleartext, cryptedpasswd), cryptedpasswd) else: return False # user not found msg = 'Hello!' if login() else 'Wrong credentials.' print(msg)