第一次编程!!
我创建了一个密码检查程序,首先检查密码是否在6到14个字符之间。如果不是,则要求用户重新输入密码。一旦接受它,然后检查密码强度并输出密码是强还是弱。我试图弄清楚如何记录每个无效的密码尝试文本文件。记录它是否小于min_length
或大于max_length
的日期和时间,我绝对丢失。
我已经查找了许多可能解决方案的站点和教程,但没有看到可能的解决方案
MIN_PASSWORD_LENGTH = 6
MAX_PASSWORD_LENGTH = 14
password = input("Enter Your Password: ")
password_length = len(password)
while True:
if password_length < MIN_PASSWORD_LENGTH:
print("Password Rejected - Password must be between 6 and 14 characters long")
password = input("Enter your password: ")
elif password_length > MAX_PASSWORD_LENGTH:
print("Password Rejected - Password must be between 6 and 14 characters long")
password = input("Enter your password: ")
else:
print("Password Accepted")
break
special = ['!','@','#','$','%','^','&','*','(',')']
letters_found = 0
digits_found = 0
specials_found = 0
for ch in password:
if ch.isalpha():
letters_found = 1
if ch.isdigit():
digits_found = 1
if ch in special:
specials_found = 1
if digits_found and letters_found and specials_found:
break
password_strength = letters_found + digits_found + specials_found
if password_strength >=2:
message = "Password is Strong!"
else:
message = ",Password is Weak!"
print("Your Password is",(password_length),"characters long.",(message))
希望能够在每次用户输入无效密码并记录日期时间时记录,并且在这种情况下它无效的原因是小于6或大于14
我建议在logging
中使用Python
模块:
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
将此添加到您要记录的代码中。您可以使用f-strings修改这些消息并记录密码。
对于第一次编程,这实际上是非常好的代码!在python中,将文本写入文件非常容易,可以使用'with'语句完成。因为您还希望记录日期,所以可以使用pythons内置的datetime模块。我不确切地知道你想要构建它的方式,因为看起来数据是相关的,你可以使用像SQLite这样的关系数据库,但我会用文本文档保持这个简单。将您在while True
的代码更改为以下内容:
with open("password_log.txt", 'a') as doc:
date = datetime.now()
dateString = datetime.strftime(date, "%m/%d/%Y %H:%M:%S")
while True:
if password_length < MIN_PASSWORD_LENGTH:
doc.write("too short," + dateString + "\n")
print("Password Rejected - Password must be between 6 and 14 characters long")
password = input("Enter your password: ")
elif password_length > MAX_PASSWORD_LENGTH:
doc.write("too long," + dateString + "\n")
print("Password Rejected - Password must be between 6 and 14 characters long")
password = input("Enter your password: ")
else:
print("Password Accepted")
break
代码的最顶部包括from datetime import datetime
。请随时询问有关此功能的任何说明。这将使其工作在最低限度,并以CSV格式存储任何日志。
这是对NightShade答案的改进,但总体上也有所改善。这是你第一次编码祝贺。我正在修改代码中的一些内容,以实现可读性,组织性,效率以及可扩展性和可重用性。
如果有什么你想让我解释的请问。此外,我修改了计算密码强度的方式,但它可以很容易地恢复到原来的密码。编辑:正如其他用户建议的那样,你不应该真正存储密码。练习可以,但你应该养成保护密码的习惯。如果您打算稍后创建登录系统,请考虑散列密码,将其存储在安全位置,然后将散列输入与存储的散列进行比较。它增加了一些保护。
from datetime import datetime # importing the date module
MIN_PASSWORD_LENGTH = 6
MAX_PASSWORD_LENGTH = 14
# Auxilliary Functions
# Enclosing in functions so that they can be reused, separated and organized
def passCheck(input_password):
date = datetime.now()
# sets the current date and time
dateString = datetime.strftime(date, "%m/%d/%Y %H:%M:%S")
# formats the string to look like m/d/t h:m:s
if len(input_password) < MIN_PASSWORD_LENGTH:
# Using text formatting for cleanliness and readibility
return(f"{dateString} ==> Password is too short: '{input_password}' (length = {len(input_password)})\n")
elif len(input_password) > MAX_PASSWORD_LENGTH:
return(f"{dateString} ==> Password is too long: '{input_password}' (length = {len(input_password)})\n")
else:
return 0
def letter_analysis(input_password):
special = ['!','@','#','$','%','^','&','*','(',')']
letters_found = 0
digits_found = 0
specials_found = 0
test = 0
for ch in input_password:
#Checking for isdigit(), isalpha() etc but adding everytime it finds it. You can change this.
test = test + 1*ch.isdigit()
letters_found += 1 * ch.isalpha()
digits_found += 1 * ch.isdigit()
specials_found += 2 * (ch in special)
# I would suggest adding 2, for example, as special characters should be valued more
return((letters_found and digits_found and specials_found, letters_found+digits_found+specials_found))
#Returning a tuple where first index will be True if letters, digits and specials exist, and second index is the count.
#Note: The count isn't a True count, since I'm counting special characters twice
## Main function
def main():
input_password = input("Enter your password: ")
try:
with open("password_attempts.txt", "a") as passFile:
# Opening text file as append, so that it doesn't erase what's there
passFile.write(passCheck(input_password))
#Passing it the result of the check function.
print(passCheck(input_password))
except TypeError:
print("Password Accepted")
#In case the return is 0, there will be TypeError. This is the case where it's accepted.
strength = letter_analysis(input_password)
#strength now holds the tuple.
evaluation = strength[0] + strength[1]
# Just an example. This is where strength is calculated and directly related to the letter analysis.
if evaluation > 5:
# Here you can use your judgement. I said 5 again as an example.
print(f"Password is strong: '{input_password}' (length/evaluation = {len(input_password)}/{evaluation})")
else:
print(f"Password is weak: '{input_password}' (length/evaluation = {len(input_password)}/{evaluation})")
main()
main()