向文本文件写入无效密码

2024-04-25 20:27:33 发布

您现在位置:Python中文网/ 问答频道 /正文

第一次编程!!
我创建了一个密码检查器,首先检查密码是否在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


Tags: and密码if记录passwordchlengthprint
3条回答

我建议在Python中使用logging模块:

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修改这些消息并记录密码。你知道吗

这是对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()

对于第一次编程,这实际上是非常好的代码! 在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格式的任何日志。你知道吗

相关问题 更多 >