first of all, I'm new to this site. Hello :)
I have a problem with a program I'm trying to make. What I'm trying to do right now is a login system - so users can enter a username and password (that they've already registered with) and then match the username and password with one in a file called 'accounts.txt'.
This means I can associate data they later generate with their account.
Here's what I have so far:
while loop == (2):
print("Welcome to login.")
verifyuser = input("Enter your username: ")
verifypass = input("Enter your password: ")
f = open("accounts.txt","r")
for line in f:
if re.match(verifyuser, line) and match(verifypass, line):
loop = (3)
Loop 3 takes it along to the rest of the program once it's verified. I know this re.match thing doesn't exactly work, but I have no idea how I could go about this, and I've tried several different routes - I don't mean to ask people to do my work for me or anything, I just can't do this specific area.
Thanks
re.match is for regular expressions, which don't seem to be used here.
https://docs.python.org/2/library/re.html#re.match
While I don't recommend user credentials in files, why aren't you using the equals operator?
if verifyuser == line:
Also, I'm not sure how both verifyuser AND verifypass could be true for the same line?
user_match = False
pswd_match = False
for line in f:
if verifyuser == line:
user_match = True
if verifypass == line:
pswd_match = True
if user_match and pswd_match:
# loop = (3)
I've actually done something just like this, I did it in a different way than you. This is what my text file looked like storing the information:
username : password
Then I would ask for the information like this:
f = open('filename.txt', 'r')
username = input('Enter your username: ')
password = input('Enter your password: ')
user = username + ' : ' + password
if user in f.read():
print('Loggin successful')
else:
print('incorrect username or password')
if you want to give the user like 5 chances you can just add in a nice little for loop.
for i in range(5):
f = open('filename.txt', 'r')
username = input('Enter your username: ')
password = input('Enter your password: ')
user = username + ' : ' + password
if user in f.read():
print('Loggin successful')
break
else:
print('Incorrect username or password')
This isn't the same as my script, mines a bit longer, but this should get the job done!
Related
I have to create code that validates whether a password:
Contains at least 1 number
Contains at least 1 capital letter
Contains at least 1 lowercase letter
Contains at least 1 special symbol
and again ask the username and password (the previous one that we entered) if enter the wrong one after 3rd attempt it will print account blocked! (can someone help to fix my code please)
import re
def main():
username = 'qqq'
password = '12q#3A'
reg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*#?&])[A-Za-z\d#$!#%*?&]"
# compiling regex
pat = re.compile(reg)
# searching regex
mat = re.search(pat, password)
# validating conditions
if mat:
print("Password is valid.")
userInput = input("What is your username?\n")
if userInput == username:
for i in range (3,0,-1):
userinput = input("Password?\n")
if userinput == password:
break
else:
print("That is the wrong password and try again")
if i==1:
print("Account BLOCKED")
else:
print(" You have succe")
else:
print("That is the wrong username.")
else:
print("Password invalid !!")
# Driver Code
if __name__ == '__main__':
main()
As stated in the comments, there are already mature libraries for the task. Also, never store passwords as plaintext.
This script will ask user 3 times for correct password, if user fails to enter valid password, print Account blocked!:
import re
def check(password):
""" Return True if password
Contains at least 1 number *AND*
Contains at least 1 capital letter *AND*
Contains at least 1 small letter *AND*
Contains at least 1 special symbol
False otherwise
"""
return bool(re.search(r'\d', password) and
re.search(r'[A-Z]', password) and
re.search(r'[a-z]', password) and
re.search(r'[#$!%*#?&]', password))
username = input('Please enter your username: ')
for attempt in range(1, 4):
password = input('Please enter your password: ')
if check(password):
print('Password is OK!')
break
print('Invalid password, attempts left {}'.format(3 - attempt))
else:
print('Account blocked!')
Prints (for example):
Please enter your username: Andrej
Please enter your password: we
Invalid password, attempts left 2
Please enter your password: wew
Invalid password, attempts left 1
Please enter your password: wew
Invalid password, attempts left 0
Account blocked!
Or:
Please enter your username: Andrej
Please enter your password: A1#a
Password is OK!
In summary I'm trying to create a password manager. The Idea is that the program would ask the user input.
If user writes "new", the program asks input on the website, username and password and then store this data in a text file in the form of a List.
Now the main problem:
I want to be able to access selected data and have the program print said data from the text file to me.
For example:
I input into the program the website "google" along with username: "potato" and password: "potato"
After that, the program asks me what else I want to do. And if I write "access google", I want to program to give me back the website, username and password that are SPECIFIC to the google input.
This is necessary, as I will be adding several different inputs.
I have no idea how to do this and have no tutor. I hope someone can give a solution I can learn from.
Below you will find the base code I have come up with.
Keep in mind that I am a beginner. Thank you.
vault = open("Passvault.txt", "r+")
list = []
action = input("What do you want to do? ")
def tit():
global title
title = input("Add website: ")
return title
def user():
global username
username = input("Create username: ")
return username
def passw():
global password
password = input("Create password: ")
return password
running = True
while running:
creation = True
tit()
user()
passw()
if action == "new":
tit()
user()
passw()
#I added a class here hoping that i could create a class with an argument referencing the title
#so that when i type access "title" in the next if statement it would print back the data
#relevant to the selected title
class new(str(title)):
list.append(tit)
list.append(user)
list.append(passw)
vault.close()
if action == "access" + title:
creation = False
print(title)
print("Username: " + username)
print("Password: " + password)
vault.close()
Here is the code. This code stores the username, password, and website name in the txt file and also prints the username and password w.r.t website name.
import re # used to search patterns.
file_name = 'Passvault.txt'
while True:
action = input("What do you want to do? ")
if action == 'new':
title = input("Add website: ")
username = input("Create username:")
password = input('Create password')
#writing data into the file
with open (file_name,'a') as f:
data = f.write(f'{title} {username} {password}\n')
if 'access' in action:#if input contains access word
website = action.split()[1].strip() #storing website name which is written after access
#reading the data
with open(file_name,'r') as f:
data = f.read()
#searching for all username password related to website
username_pass = re.findall(f'{website}\s+(.*?)\n',data,re.S)#example google sachin 1234
print('Website: ',website)
print('Username, Password',username_pass)
I'm going to give you a more conceptual answer than code, because this is a more long term type of deal.
What you're going to want to do is use json files and dictionaries to store your data so you can search by keys (see the dictionaries link).
Once you've done that you're going to want to wrap everything in a while loop inside a def that gets user input like so:
def get_input():
permitted_actions = ['new', 'access', 'exit']
while True:
action = input("What do you want to do? Valid actions: new, access or type EXIT to end the program.").strip().lower()
if action not in permitted_actions:
print(f"{action} is not a valid action!")
elif action == 'new':
#call another function to do stuff here
elif action == 'access':
#call another function to do stuff here
elif action == 'exit':
print("Shutting down...")
break
I would highly recommend against creating your own actual vault for a password manager until you're much more experienced if you actually intend to use this, otherwise feed it fake passwords and whatnot and learn.
Now when you're adding website data you'll read your dictionary (see the dictionary link) and get the key associated with said website if it exists and then update the info that the user gives.
When you're accessing a website's data you just go to the dictionary (see the dictionary link) and grab the info relating to that website key if it exists.
Remember, you're going to be loading that dictionary from a json file (see the json link).
If you were to make this program an actual program someone would use you'd use a proper database of some sort (python3 has sqlite support natively) and use a database with encryption and master passwords.
I hope this points you in the right direction.
You can save the values as a dictionary with a list as the username and password then use literal_eval to convert the string dict into a dict and access the username and password as well as storing other websites with its own usernames and passwords.
website = 'google'
username,password = 'potato', 'potato'
filename = "yourfilehere"
with open(filename, w) as f:
f.write(str({website: [username,password]}))
#This will save your data as a string dictionary will the data above
#then read the file, get the dictionary and convert it then use its values
from ast import literal_eval
with open(filename, 'r') as f:
data = f.read()
data = literal_eval(data)
#Then search dictionary for website
found = data.get(website)
#Then if it was successful get the username and password
username = found[0]
password = found[1]
As long as you only have the dictionary created as a string in the file you are reading you can use this ethod to save as many website with the allocated username and password saved with it.
You can add a input() into the code to check which site the user wants the username and password for and then search for it in your dictionary.
search = input("Enter the website: ")
try:
found = data.get(search)
#add code here to get username and password
except:
print("failed to find a website matching: %s" % search")
The for loop is skipping over the if statements when the loop is complete or at least thats what I think it is doing. Let me know what I need to revise. The dictionary has usernames and passwords stored in from inputted new users.
import json
users = {}
def create_new_login():
new_username = (input("Please enter a username: "))
new_password = (input("Please enter a password: "))
filename = 'login.json'
if new_username in users.keys():
input("Please input a new username")
elif new_password in users.values():
input("Please input a new password")
else:
users.update({new_username : new_password})
with open(filename, 'a') as file_object:
json.dump(users, file_object)
def check_username():
"""Checks username and password"""
#User inputs username and password
username_input = input("Please enter your username: ")
for key in users.keys(): #Checks username and password
if username_input == key:
check_password()
else:
print("Incorrect login")
def check_password():
password_input = input("Please enter your password: ")
for value in users.values():
if password_input == value:
print("Welcome back " + users)
welcome = input("Are you a new user?(yes or no): ")
if welcome == 'yes':
create_new_login()
if welcome == 'no':
check_username()
I expect if the username entered is in the dictionary then it will run the check_password function and do the same task for the password. But upon completion it will say "Welcome back " + the username inputted. Also if someone could explain how instead of using users for the welcome back I could use the password given to find the key for that value in the dictionary.
You've written the json file but are not reading from it. Every time you re-run the program you start at the top and initialize users = {}. Put a print statement in the for loop and you will find that users.keys() is dict_keys([]) is empty. And this makes the for loop "skip over" if because it fails the condition. What you ought to do is to read from the json file and then check the condition.
Hi everyone i need help for my computing project but cant find an answer on google. Im trying to make a basic login system and have 2 lists, one list with usernames and one with passwords:
usernames[username1, username2, username3, etc]
passwords[password1, password2, password3, etc]
i want to ask the user for a username and password input and check if they are in the corresponding lists. However i cant work out how to do it without someone being able to login using their username and someone else's password.
My current code is:
def Login():
usernames = [username1, username2, username3]
passwords = [password1, password2, password3]
user = input("Please enter your username: ")
pw = input("Please enter password: ")
x = 0
for x in range(len(usernames)):
if user == usernames[x] and pw == passwords[x]:
print("Login Successful")
elif user == usernames[x] and pw != passwords[x]:
print("Password does not match")
Login()
else:
print("User not recognised")
Login()
x = x + 1
I want to be able to check what position the username they gave me is in the list and then look for that position in the passwords list and if that password is the one they gave, they can login.
Thank you!
You can use zip to iterate over your list. And use enumerate if you need to find the position.
Demo:
def Login():
usernames = ['username1', 'username2', 'username3']
passwords = ['password1','password2', 'password3']
user = input("Please enter your username: ")
pw = input("Please enter password: ")
for i, x in enumerate(zip(usernames, passwords)):
if user == x[0] and pw == x[1]:
print("Login Successful")
print("Index Position ", i)
elif user == usernames[x] and pw != passwords[x]:
print("Password does not match")
print("Index Position ", i)
Login()
else:
print("User not recognised")
Login()
I am a little stuck with my code I am trying to make a login system where the user can login to their account and use the commands that I have set, but i wanted add some extra input so that the user can register to the login system and use the commands I have set. I wanted to store the input made by the user permanently in a different variable each time so that when the user restarts the peice of code they can log in to the system and they wouldn't need to register again.
Here is the piece of code that I have created so far:
print ("Welcome!")
print ("Would you like to register")
loop = True
while (loop == True):
username = input ("username: ")
password = input ("password: ")
print ("register here if you don't have an account")
username1 = input ("name: ")
print ("this is what you use to login to the system")
username2 = input ("username: ")
username3 = input ("password: ")
if (username == "rohit" and password == "rodude") :
print ("hello and welcome " + username or )
loop = False
loop1 = True
else:
print ("invalid username and password")
while(loop1 == True):
command = str(input(username + "{} > >"))
if(command.lower() == "exit"):
loop1=False
elif(command.lower() == "hi"):
print("Hi " + username + "!")
else:
print ("'" + command + "' is an invalid command!")
Hey guys your ways are too complicated all you could do is this
name = open("usernames.txt", "w") #opens file usernames.txt and gets ready to write to it
file = input("please type some text: ") #asks user for text in code
name.write(file) #writes contents in file to usernames.txt
name.close() #closes file
open1 = open("usernames.txt", "r") #opens file to read it
print (open1.read()) #prints whatever is in the text file
You can't use variables for local storage. If you want information to persist across program runs, you need to store it in a persistent location - typically a disk file or a database. There are a lot of modules available to make this easier, Pickle (as noted in klashxx's response) is an excellent one for simple scenarios.