0

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

4

3 回答 3

0

我建议在以下位置使用该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 字符串来修改这些消息并记录密码。

于 2019-03-25T09:32:45.543 回答
0

这是对 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()
于 2019-03-25T12:00:50.843 回答
0

对于第一次编程,这实际上是非常好的代码!在 python 中,将文本写入文件非常容易,可以使用“with”语句来完成。因为您还希望记录日期,所以您可以为此使用 python 内置的 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 的格式存储任何日志。

于 2019-03-25T09:47:18.920 回答