why closes my python program without fully executing? - python

I am completely new to programming and started a few days ago with learning Python(v.3.8.8). I wanted to make a small password manager, but with a little secret function(I think that's not important and it would take too much time to describe). Anyways I converted the main.py to a .exe with auto-py-to-exe but every time I wanna execute the .exe I can only enter my Login data and the window instantly closes but in Pycharm everything works totally fine. Does anyone know why?
EDIT: It works now, there was no missing "Input()" or stuff like that, I had a spelling mistake in my code and pycharm ignored it!
from cryptography.fernet import Fernet
welcome = input("Login(1), New User (2): ")
def new_user(): # creates a new user and safe the Username and pw in a .txt
print("The login is just for the safety of your data, everything is stored on your local PC!")
username = input("Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
key = Fernet.generate_key()
f = Fernet(key)
f.encypt(b'password')
file = open(username + ".txt", "w")
file.write(username + ":" + password)
#file.close()
login() # go to login after everything is safed in the .txt
else:
print("Passwords do NOT match!")
def login(): # checks if the entered username and pw match with the .txt content
login1 = input("Login:")
login2 = input("Password:")
file = open(login1 + ".txt", "r")
pw = file.readline()
#file.close()
if pw == login1 + ":" + login2: # infinte trys to enter the username and pw
print("Welcome " + login1)
pwrequest()
else: # returns to login() if the pw is incorrect
print("Incorrect username or password. Please try again")
login()
def pwrequest():
q = input("safe new Password(1), show safed passwords(2)")
if q == "2":
data() # show all saved pw
if q == "1":
newdata() # go to data() if the user want to add a new pw or
# want to acces the hidden part
def data():
file = open('1.txt', 'r') # prints all saved passwords
file_pw = file.read()
print(file_pw)
file.close()
c = input("Press (1) to delete something and press (2) to log out.")
if c == '1':
delete() # delete a pw or acces to hidden part
if c == '2':
login() # simple logout system, probably have to change this to something more intermediate
def newdata(): # safes the data in variables and put it in a .txt file
company = input("Enter the companys name: ")
username = input("Enter your username: ")
password = input("Enter your password: ")
print(company + username + password + ", is everything correct?")
a = input("y/n")
if a == "y":
file = open("1.txt", "w")
file.write(
"Company: " + company + "\n" + "Username: " + username + "\n" + "Password: " + password + "\n" + "\n")
file.close()
pwrequest() # return to pwrequest()
if a == "n":
newdata() # return to newdata() if something is incorrect
secretWord = "CompanyUsernamePassword" # define the secret word to finaly acces the hidden part
if company + username + password == secretWord:
secrettest() # go to secrettest() to enter the secret word
def delete(): # just simple code that delete specific content of the pw .txt
name = input("Please enter the Company, Username and password you wanna delete: ")
with open("1.txt", "r") as f:
lines = f.readlines()
with open("1.txt", "w") as f:
for line in lines:
if line.strip("\n") != name:
f.write(line)
def secrettest():
key = Fernet.generate_key()
f = Fernet(key)
truepass = f.encrypt(b"Test1234")
trys = 3
while trys != 0: # checks if you entered the correct pw and if not count 2 times
password = input("Pls enter the password: ")
d = f.decrypt(truepass)
if password == d.decode():
print(truepass)
break
else:
print("Wrong password!")
trys -= 1
if trys == 0:
print("You entered the wrong password to many times!")
if welcome == "1": # should probably try to move that to the top
login()
if welcome == "2": # this too
new_user()

I think I know why the .exe always closes. I executed the .exe in the windows cmd, and got this error "AttributeError: 'Fernet' object has no attribute 'enrcypt'". I'm kinda sure that this is the part that caused the trouble. I'm just wondering why pycharm just ignored this error...

Related

Password Encryption with Fernet

I am new in python and I am doing these kind of little projects so that I can build myself.
This is a little project which will only add and view the username and passwords with a master password. I was able to add username and passwords with encrypted the passwords in the file. But to view the passwords it shows me two problems in 23 and 39 line. And also the master password is not working.
from cryptography.fernet import Fernet
'''
def write_key():
key = Fernet.generate_key()
with open("key.key", "wb") as key_file:
key_file.write(key)'''
def load_key():
file = open("key.key", "rb")
key = file.read()
file.close()
return key
master_pwd = input("What is the master password? ")
key = load_key() + master_pwd.encode()
fer = Fernet(key)
def view():
with open('passwords.txt', 'r') as f:
for line in f.readlines():
data = line.rstrip()
user, passw = data.split("|")
print("User:", user, "| Password:",
fer.decrypt(passw.encode()).decode())
def add():
name = input("Account name: ")
pwd = input("Input password: ")
with open('passwords.txt', 'a') as f:
f.write(name + "|" + fer.encrypt(pwd.encode()).decode() + "\n")
while True:
mode = input("Would you like to add a new password or view existing ones?(Add/View):\nOtherwise press 'Q' to Quit: \n").lower()
if mode == "q":
break
elif mode == "view":
view()
elif mode == "add":
add()
else:
print("Invalid mode.")
continue
The problems are shown in this picture.

Writing to text file formatting

I have an assignment to make a simple task manager/todo list. This code block is just the part of the program that handles login, new username and password registration. When the user registers that input is written to a text file called user.txt.
Whenever it writes to the text file, it writes like this:(['admin', 'adm1n'])
instead, it should write it like this:admin, adm1n
user_file = open("user.txt","r+")
login = False
while login == False:
new = input("Are you a new user? Y/N:\n").lower()
if new == "y":
print("Please register a new username and password:\n")
new_user1 = input("Please enter a new username:\n").split()
new_pass1 = input("Please enter a new password:\n").split()
new_user2 = input("Please confirm your username:\n").split()
new_pass2 = input("Please confirm your password:\n").split()
user_pass1 = new_user1 , new_pass1
user_pass2 = new_user2 , new_pass2
if user_pass1 == user_pass2:
user_file.write(f"{user_pass2},")
user_file.seek(0)
break
elif new == "n":
username = input("Enter your username:\n")
password = input("Enter your password:\n")
valid_user = username
valid_password = password
for line in user_file:
valid_user, valid_password = line.split(", ")
if username == valid_user and password == valid_password:
login = True
if login == False:
print("Incorrect details! Please enter a valid username and password")
What am I doing wrong? I'm sure it's something small.
Thanks in advance!
Because you are making a tuple there. Instead, you should create a string. Here is the corrected version of your code
user_pass1 = new_user1 + ',' + new_pass1
user_pass2 = new_user2 + ',' + new_pass2
if user_pass1 == user_pass2:
user_file.write(f"{user_pass2},")
user_file.seek(0)
break
Thanks for your feedback everyone.
I managed to get it figured out. I added an index to it to print the string and it worked just fine.
user_pass2 = new_user2 , new_pass2
if user_pass1 == user_pass2:
#Writes username and password to text file in format requested.
user_file.write(f'\n{user_pass2[0]}, {user_pass2[1]}')

Why does my Python program fail to read the second line of my data file?

I am learning python. I wanted to learn to work with text files, so I decided to make a simple console program.
The program does the following:
Asks if you had already a profile.
If no, then asks to create a username and a password. The information is saved in a text file.
If yes, then asks to input your password and username.
When the user doesn't have a profile, everything works well. When the user has a profile and wants to log in, it doesn't work and I don't know why.
The username is saved in the first line of the text file and the password in the second line, so, I use readlines()[0] and readlines()[1].
The username is recognized correctly, but the password doesn't. I get this error
Traceback (most recent call last):
File "Archivo de prueba.py", line 4, in <module>
print(text_file.readlines()[1])
IndexError: list index out of range
This is the code I wrote:
text_file = open("Archivo de prueba.txt", "r+")
def ask_for_account():
global has_account
has_account = input("Do you have an account? (Write \"Yes\" or \"No) ")
ask_for_account()
def create_profile():
create_user = str(input("Type your new username: "))
create_password = str(input("Type your new password: "))
text_file.write(create_user)
text_file.write("\n")
text_file.write(create_password)
def login():
username = text_file.readlines()[0]
password = text_file.readlines()[1]
current_user = input("Type your username: ")
current_password = input("Type your password: ")
if str(current_user) == str(username) and str(current_password) == str(password):
print("Succesfully logged in.")
else:
print("Invalid username or password")
if has_account == "No":
create_profile()
elif has_account == "Yes":
login()
else:
print("Invalid input")
ask_for_account()
text_file.close()
The following code works. I added a few comments to indicate changes.
def ask_for_account():
return input("Do you have an account? (Enter 'Yes' or 'No') ")
def create_profile():
create_user = str(input("Type your new username: "))
create_password = str(input("Type your new password: "))
# Open the file for writing and close it after use.
text_file = open("Archivo de prueba.txt", "w")
text_file.write("{}\n".format(create_user))
text_file.write("{}\n".format(create_password))
text_file.close()
def login():
# Open the file for reading and close it after use.
text_file = open("Archivo de prueba.txt", "r")
lines = text_file.readlines()
text_file.close()
# remove the newline at the end of the input lines.
username = lines[0].rstrip()
password = lines[1].rstrip()
current_user = input("Type your username: ")
current_password = input("Type your password: ")
if current_user == username and current_password == password:
print("Succesfully logged in.")
else:
print("Invalid username or password")
#
# Put program logic in one place after the methods are defined.
#
has_account = ask_for_account()
if has_account == "No":
create_profile()
elif has_account == "Yes":
login()
else:
print("Invalid input")
username = text_file.readlines()[0]
password = text_file.readlines()[1]
The first call to readlines() consumes the entire file and there are no lines remaining for the second call to read, so it returns an empty list.
Read the file once and save the lines in a list, then pick the desired lines from the list:
file_lines = text_file.readlines()
username = file_lines[0]
password = file_lines[1]
Also, be aware that readlines() puts a carriage return \n at the end of every line, so you might have to strip that off depending on how you use these values.

How do I loop my password/username login page and read the password/username from an external file?

I'm aware of the multiple posts and sources regarding how to loop and read from a text file. I'm sorry to be that guy but I'm a recent noob at Python and I'm writing this at 1:00 in the morning.
As the title suggests, how do I loop my login page so that if the user enters details incorrectly then they get another chance to try, until they have entered details correctly. The password/username also needs to be read from an external file.
My code:
print ("\nEnter details to access wallet...\n")
username = 'Janupedia'
password = '12345'
userInput = input("What is your username?\n")
if userInput == username:
userInput = input("Password?\n")
if userInput == password:
print("Welcome!")
print('\n--------------------------------------------------------\n')
print ("BTN = 0.10")
print ("= £315.37")
else:
print("That is the wrong password.")
else:
print("That is the wrong username.")
print('\n--------------------------------------------------------\n')
Let's say your text file (credentials.txt) reads:
Janupedia
12345
Maybe something like this will work for you. I've commented the code that I added. You probably want to name the credentials file something else.
print ("\nEnter details to access wallet...\n")
"""
Open File
"""
with open("Credentials.txt", "r") as f:
array = []
for line in f:
array.append(line) #stores username and password
username = array[0]
password = array[1]
login = 0 #initial login status
while login == 0: #as long as login status = 0 loop repeats
userInput = input("Username?")
if username.strip(' \n') == userInput.strip(' \n'):
userInput = input("Password?")
if password.strip(' \n') == userInput.strip(' \n'):
login = 1 #login successful set login status to 1 thus breaking loop
else:
print("Incorrect")
else:
print("Incorrect")
print('\n--------------------------------------------------------\n')
# Login successful loop finished
print("Welcome!")
print('\n--------------------------------------------------------\n')
print ("BTN = 0.10")
print ("= 315.37")
So you want to loop it. Where would a good place for that be? How about when we ask for a question.
Now, look at the condition where we get the right username and password. We don't want to handle it inside the loop. The loop is only there to get the correct username and password.
print("\nEnter details to access wallet...\n")
username = "Janupedia"
password = "12345"
userInput = ""
while userInput != password:
userInput = input("What is your username?\n")
if userInput == username:
userInput = input("Password?\n")
if userInput == password:
break
else:
print("That is the wrong password.")
else:
print("That is the wrong username.")
print("Welcome!")
print("\n--------------------------------------------------------\n")
print("BTN = 0.10")
print("= £315.37")
todo_list = open("Credentials", "a")
todo_list.write("Username = Janupedia + Password = 12345")
todo_list.close()
print("\n--------------------------------------------------------\n")
Now to read your username/password from a file. Let's make it simple. The first line is the username and the second line is the password. There are no other items.
Now create a proper function.
def read_credentials_from_file(filename):
"""Read the file and return (username, password).
File contents are first line username and second line password.
"""
# Using the `with` statement is current best practice.
with open(filepath, "rt") as user:
username = user.readline().strip()
password = user.readline().strip()
return username, password
Now fix your code to use the function.
username, password = read_credentials_from_file(...)
Note in the function we strip line endings. If you are using Python 3.7, use the breakpoint function to step through the code and watch what it is doing.
do something like this:
password = "password"
username = "username"
theirUsername = input("What is your username")
theirPassword = input("What is your password")
while theirUsername != username or theirPassword != password:
print("incorrect")
theirUsername = input("What is your username")
theirPassword = input("What is your password")
print("correct")
You can read from an external file with file = open("externalfile.txt","r") then do text = file.read() and if the file is formatted as
username
password
do text = text.split("\n") and then username = text[0] and password = text[1]
this is what it should look like with an explanation:
file = open("password.txt","r") #this opens the file and saves it to the variable file
text = file.read() #this reads what is in the file and saves it to the variable text
text = text.split("\n") #this makes the text into a list by splitting it at every enter
username = text[0] #this sets the username variable to the first item in the list (the first line in the file). Note that python starts counting at 0
password = text[1] #this sets the password variable to the second item in the list (the second line in the file)
theirUsername = input("What is your username") #gets username input
theirPassword = input("What is your password") #get password input
while theirUsername != username or theirPassword != password: #repeats the code inside while theirUsername is not equeal to username or theirPassword is not equal to password
print("incorrect") #notifies them of being wrong
theirUsername = input("What is your username") #gets new username input
theirPassword = input("What is your password") #gets new password input
print("correct") #tells them they are corrected after the looping is done and the password and username are correct

How can I make a basic program that allows someone to sign in to an account previously created?

I am trying to make a python program that will allow a user to sign up or sign in, and I am currently doing so by creating a file that stores every username and its password. Right now, it is not writing to the file, and I was wondering if anyone could tell me what I'm doing wrong. Please forgive me if it is a stupid error, I am not very experienced with python, but I can still make a basic program. This is my code:
# -*- coding: utf-8 -*-
from time import sleep
def signin():
usrlist = open("users.txt", 'w+')
complete = False
while (complete == False):
usr = raw_input("Username: ")
pwd = raw_input("Password: ")
usrinfo = (usr + ":" + pwd)
if (usrinfo in usrlist.read()):
print("Welcome back " + usr + ".")
complete = True
else:
print("Username or Password incorrect. Please try again.")
def signup():
usrlist = open("users.txt", 'w+')
usravailable = False
while (usravailable == False):
newusr = raw_input("Please choose a Username: ")
if (newusr in usrlist.read()):
print("Username taken. Please choose again.")
else:
usravailable = True
newpwd = raw_input("Please choose a password: ")
oldusrlist = usrlist.read()
usrlist.write(oldusrlist + newusr + ":" + newpwd + ".")
print("Thank You. Please Sign in.")
signin()
print("Please Choose An Option:")
print("1. Sign In")
print("2. Sign Up")
inorup = input()
if (inorup == 1):
signin()
elif (inorup == 2):
signup()
Also, if you have any suggestions about how I could do this differently, or better(even if it's using a different language) Thank you and I appreciate your help.
EDIT:
If anyone can give me information on doing a program like this either using JSON, javascript, or multiple files that can store larger amounts of data about each account, please tell me how in the comments or an answer. I appreciate the help.
To fix your not saving issue, you need to do two changes:
1) in your signin() routine, change the line 'usrlist = open("users.txt", 'w+')' into 'usrlist = open("users.txt", 'r')
2) in your singup() routine, after the line 'usrlist.write(oldusrlist + newusr + ":" + newpwd + ".")', add: 'usrlist.close()'
Then you should be able to see the stuff got saved.
here is a way to use json
import json
import os
FILENAME = "./f.json"
# init the data file
def init_data():
with open(FILENAME, "wb") as f:
json.dump({}, f)
def load_content():
with open(FILENAME) as f:
infos = json.load(f)
return infos
def save_content(content):
with open(FILENAME, "w+") as f:
json.dump(content, f)
return True
def save_info(username, password):
infos = load_content()
if username in infos:
return False
infos[username] = password
save_content(infos)
return True
def sign_in(username, password,):
status = save_info(username, password)
if not status:
print "username exists"
def login(username, password):
infos = load_content()
if username in infos:
if password == infos[username]:
print "login success"
return True
else:
print "password wrong"
return False
else:
print "no user named %s" %username
if __name__ == "__main__":
# here is some simple test
os.system("rm -f %s" %FILENAME)
if not os.path.exists(FILENAME):
init_data()
# login fail
login("hello","world")
# sign_in
sign_in("hello", "world")
# login success
login("hello","world")
# sign_in fail
sign_in("hello", "world")
# login fail
login("hello", "hello")

Categories

Resources