I am getting a problem in my code. I created a program which creates an account, saves username and password in a .txt file. Then asks for login and it checks whether the username and password is corrent or not. But everytime the else condition is executing. And i am getting output "You don' have any account". Please help. Thanks in advance.
# MyProgram: Account Verification
print "\ncreate account:\n"
f = open("data.txt",'w+')
def create():
user_name = raw_input("Enter username >> ")
password = raw_input("Enter password >> ")
confirm = raw_input("Enter password to confirm >> ")
if password == confirm:
f.write(user_name+"\n"+password)
f.close()
print "Account created"
else:
print "\nPassword not matched\n\n Enter details again:\n"
create()
create()
new = open("data.txt")
un = new.readline()
pw = new.readline()
new.close()
def login():
print "\nLogin:\n"
name = raw_input("Enter username >> ")
if name == un:
pas = raw_input("Enter password >> ")
if pas == pw:
print "Welcome!"
else:
print "Wrong password"
login()
else:
print "You don't have any account"
login()
readline includes the newline character at the end of the line, so you're probably comparing e.g. "hunter2\n" to "hunter2". Try stripping the whitespace off first.
un = new.readline().strip()
pw = new.readline().strip()
Alternatively, it may be preferable to store/retrieve your usernames and passwords in some way other than writing strings to and reading strings from a plain text file. For very lightweight applications, simple serialization like the pickle or json libraries might suffice; but anything really serious would benefit from a proper database. With any of these, you probably won't need to worry about the behavior of readline() at all.
Related
I have a program that asks the user for a username and password, then checks a text file to see if that username/password are in there. Then it is supposed to print the contents of the text file to screen. A couple of issues:
It ALWAYS takes two attempts to successfully log in, even if the username/password are correct.
On successful login, the contents of the text file are not printed.
Would very much appreciate some guidance on why these things are happening, and how they can be resolved!
def option3():
print('\nGelos Enterprise User Accounts\n')
global index_num,userName,passWord,balances,username,password
username=input("Enter your username : ")
password=input("Enter your password : ")
fileRead=open('accounts.txt','r')
fileContents = fileRead.read()
flag=False
while True:
line=fileRead.readline()
lineLength=len(line)
if lineLength==0:
break
lineItem=line.split()
if username.strip()==lineItem[0] and password.strip()==lineItem[1] :
print("\nHello",username,"you have logged in successfully."'\n')
print("Displaying all usernames and passwords: \n")
time.sleep(2)
print(fileContents)
flag=True
break
if flag==False:
print("\nThe user is not found.Please re-enter your username and password.\n")
option1()
I would try something like this.
def print_file_contents(file_name):
with open(file_name) as f:
for line in f:
print(line)
def option3():
print('\nGelos Enterprise User Accounts\n')
global index_num,userName,passWord,balances,username,password
username=input("Enter your username : ")
password=input("Enter your password : ")
file = 'accounts.txt'
flag = False
for line in open(file).readlines():
lineItem=line.split()
if username.strip() == lineItem[0] and password.strip() == lineItem[1] :
print("\nHello",username,"you have logged in successfully."'\n')
print("Displaying all usernames and passwords: \n")
time.sleep(2)
print_file_contents(file)
flag=True
break
if not flag:
print("\nThe user is not found.Please re-enter your username and password.\n")
option1()
However I haven't really modified what the code does, and I suspect the issue comes with how the text file is formatted.
I also assume this is a project and not actual passwords stored in a .txt file which wouldn't be a great idea.
My question is that I am creating a login system in python. This system is very simple. The user type login , his email and password. The program checks from a file whether the email or password is correct or not. But I am running into some issues with that. So I first opened the file then asked the user if he wants to log in or signup. If he types login the program asks for email and password and check in the file whether this matches or not. The program takes input correctly but at the time of checking it fails. It does not give an error but it does not print the desired statement. This my code
with open('Data_Login_System.txt' , 'r') as data:
user_input = input("""Type Either Login or SignUp> """)
if user_input.lower() == "login":
Email = input("""Type your Email> """)
Password = input("""Type Your Password> """)
for line in data:
if line.lower() == f"email : {Email.lower()}" or line.lower() == f"password : {Password.lower()}":
print("Logged in")
These are the contents of the file.
Email : shabeebasghar123#gmail.com
Password : shabeebasghar123
Whenever I enter the correct email and password it should print logged in but it does not the program just run finely and nothing at the end
This is the execution of the program
Type Either Login or SignUp
> login
Type your Email
> shabeebasghar123#gmail.com
Type Your Password
> shabeebasghar123
It worked by just doing line.lower().strip() intead of just line.lower()
First of all you got to use a readlines() function to read lines from the .txt file with a loop. You could actually read a lines without a loop on that one. See code below.
lines = data.readlines()
print(data)
The out put for that would be:
['Email : mail#gmail.com\n', 'Password : passwd123'].
So I would try a bit different approach. Make sure that you don't have any unwanted extra lines in txt file.
user_input = input("Type Either Login or SignUp")
if user_input.lower() == "login":
email = input("""Type your Email""")
password = input("""Type Your Password""")
with open("data.txt", 'r') as f:
t_mail = f.readline()
t_passwd = f.readline()
if f"Email : {email}\n" == t_mail and f"Password : {password}" == t_passwd:
print('You are now logged in')
This works fine for me.
This is my code:
users = []
users.append([username, password])
usersFile = open("users.txt","w+")
for users in users:
usersFile.write("%s" % users)
usersFile.close()
def loginFunction():
userEntry = ""
foundName = 0
while userEntry == "":
userEntry = raw_input("Enter your username: ")
usersFile = open("users.txt", "r")
lines = usersFile.readlines()
usersLen = len(users)
for index in range (0, usersLen-1):
if userEntry == users[index, 0]:
foundName = 1
passwordEntry = raw_input("Enter your password: ")
if passwordEntry == users[index, 1]:
print "Username and passwords are correct"
else:
print "incorrect"
userEntry = ""
if foundName == 0:
print "Username not recognised"
userEntry = ""
I have produced a program that registers the username and password of a user. I have checked the files and it saves the username and password successfully but when I try to login using the correct username that I know is in the file as a list, it still always comes up "Username not recognised". Any ideas as to why this might be?
It looks like you're writing out the user/passwords, as lists, as single lines in the file. Then when you read it back, each pair is read back as one string. readlines() doesn't automatically convert text back to a list object. If you want to do that, you might use Pickle instead. Pickle should let you save the entire users list of lists object all at once.
Also to be pythonic your for loop should iterate over the list directly. If you need the current index, use for i, user in enumerate(users). Using range(len(users)) is suboptimal in python. You can then use user[0] to get the username and user[1] for the password.
I've made a few changes to your program. Firstly, I've changed it to use the modern print function instead of the print statement. The print function is available in Python 2.6 and later. It's more powerful than the old print statement, and IMHO it's a good idea to start using it in preparation for Python 3 (which doesn't have the print statement).
To simplify reading & writing the username & password data we can use the standard csv module. It's not strictly necessary for this simple task, but it means we don't have to worry about the messy details of parsing the name and password strings. Eg, if the strings contain spaces or quotes, the csv will handle them correctly. Note that in Python 2 CSV files must be opened in binary mode, but in Python 3 they must be opened in text mode. This is rather annoying when you're trying to write code that runs correctly on both versions.
The easy way to look up a password given the username is to use a dictionary with the username as the key and the password as the value. This is much more efficient than scanning through a list row by row looking for a match.
Of course, in a real program we would never store passwords as plain text. That's extremely insecure! The usual procedure is to store a hashed version of the password, using a strong cryptographic hash function applied a very large number of times to make it a time-consuming operation. For further info please see PBKDF2, scrypt, and bcrypt.
Also, it's bad practice to let a potential attacker know that a username is valid but that the password they submitted is invalid. That allows them to easily build a list of valid usernames. Instead, you should always ask for the password, even if the username is invalid.
from __future__ import print_function
import csv
users = [
['Alice', 'aardvark'],
['Bob', 'bobcat'],
['Steve', 'swordfish'],
]
# Save the users list to a CSV file
users_filename = "users.txt"
with open(users_filename, "wb") as f:
writer = csv.writer(f)
writer.writerows(users)
def login_function():
# Load the usernames & passwords into a dictionary
with open(users_filename, "rb") as f:
users = dict(csv.reader(f))
# Give the user 3 chances to login
for i in range(2, -1, -1):
user_entry = raw_input("Enter your username: ")
password_entry = raw_input("Enter your password: ")
if user_entry in users and password_entry == users[user_entry]:
print("Username and password are correct")
return True
else:
print("Username and password are invalid")
print(i, "login attempts remaining")
print("Login failed")
return False
print(login_function())
demo
Enter your username: Alan
Enter your password: runner
Username and password are invalid
2 login attempts remaining
Enter your username: Alice
Enter your password: aardvark
Username and password are correct
True
I am new to programming and am wondering if this is possible. I am trying to create a password protected script, where the password is entered once and then required to progress the script the next time the script is opened. I am storing and encrypting the password in a file, and then checking to see if the file exists the next time the script is opened. The problem I am running into is checking to see if the passwords match, since the original password is in a function as a local variable.
def createFile():
pw = input('Enter Password: ')
pw2 = input('ReType Password: ')
if pw == pw2:
newPw = encrypt(pw, 10) #encodes the string with a key in a seperate encrypt function
pwFile = open('PW.txt', 'a')
pwFile.write(newPw)
pwFile.close()
else:
print('The passwords do not match')
createFile()
if os.path.isfile('PW.txt'):
print('File exists')
pwCheck = input('What is the password? ')
#I can not check pwCheck == pw since pw is a local var.
#progression of script here
else:
createFile()
I know that it is considered bad for to make a local variable global. Is there a way to restructure what I have so far to make this work? As I wrote this, I think I may have came up with a possible solution but I do not have time to test it now. Do I run the same encrypt function with the same key for pwCheck and then check if it is == to the first line of PW.txt? Is that correct and/or are there other solutions?
Thank you.
Using Windows, Python 3.4
Instead of "encrypt", perhaps use a 1-way hash.. Then, you can hash the subsequently entered password and check it versus the hash stored in the file... Something like:
def createFile():
pw = input('Enter Password: ')
pw2 = input('ReType Password: ')
if pw == pw2:
newPw = sha.new(pw).digest
pwFile = open('PW.txt', 'a')
pwFile.write(newPw)
pwFile.close()
else:
print('The passwords do not match')
createFile()
if os.path.isfile('PW.txt'):
print('File exists')
pwCheck = input('What is the password? ')
previous = open('PW.txt', 'r')
prevPass = previous.read()
hashed = sha.new(pwCheck).digest()
if (hashed==prevPass):
#progression of script here
else:
createFile()
I really hope that this is just an exercise, because if you care about security, you should be using some other authentication mechanism to gate access. Most obviously, unix permissions, and sudo to gate access.
Assuming it is an exercise only, simply have a function which checks the input against the file. Something like:
def doAuth():
isAuthed = getPassInput() == getPassFromFile()
if isAuthed:
return True
else:
raise HellNoException("Passwords differ")
Let's say that I have a file with this in it:
passcode
Now, what I want to do is have some code with user input that should test if what the user entered what is equal to what is in the file. Is there a any way I can do this? Here is the code that I already have:
with file('test.txt') as f:
s.strip('\n')
s = f.read()
inp = raw_input()
if inp == s:
print "Access granted"
else:
print "Access denied!"
I took your code and added the following line at the end:
print repr(inp), repr(s)
The output I got was
'passcode' 'passcode\n'
Apparently raw_input() included the newline at the end. Strip that off and it should work.
A quick edit you could also do is save s in another Python file and call it in your code using import as below. The Python file with the data for s is called "data.py" in the same directory.
But I do agree with others about using a hash scheme if you're checking passwords.
import data
inp = raw_input()
if inp == data.s:
print "Access granted"
else:
print "Access denied!"
Here is an example of a simple password username.
import time
import sys
username = raw_input('ENTER USERNAME: ')
password = raw_input('ENTER PASSWORD: ')
if username == '(enter any name here)':
if password == '(enter any password here)':
print 'ACCESS GRANTED'
else:
print 'ACCESS DENIED'
time.sleep(.05)
sys.exit()