验证密码 - Python

Posted

技术标签:

【中文标题】验证密码 - Python【英文标题】:Validation of a Password - Python 【发布时间】:2017-04-28 07:34:06 【问题描述】:

所以我必须创建验证密码是否的代码:

至少有 8 个字符长 至少包含 1 个数字 至少包含 1 个大写字母

代码如下:

def validate():
    while True:
        password = input("Enter a password: ")
        if len(password) < 8:
            print("Make sure your password is at lest 8 letters")
        elif not password.isdigit():
            print("Make sure your password has a number in it")
        elif not password.isupper(): 
            print("Make sure your password has a capital letter in it")
        else:
            print("Your password seems fine")
            break

validate()

我不确定出了什么问题,但是当我输入一个带有数字的密码时,它一直告诉我我需要一个带有数字的密码。有什么解决办法吗?

【问题讨论】:

check if a string contains a number的可能重复 Checking the strength of a password (how to check conditions)的可能重复 【参考方案1】:

password.isdigit()不检查密码是否包含数字,它会根据:

str.isdigit():如果字符串中的所有字符都是数字,则返回true 并且至少有一个字符,否则为假。

password.isupper() 不检查密码中是否有大写字母,它会检查所有字符:

str.isupper():如果字符串中的所有大小写字符都是 大写且至少有一个大小写字符,否则为假。

如需解决方案,请在check if a string contains a number查看问题和接受的答案。

您可以构建自己的hasNumbers()-function(复制自链接问题):

def hasNumbers(inputString):
    return any(char.isdigit() for char in inputString)

还有一个hasUpper()-函数:

def hasUpper(inputString):
    return any(char.isupper() for char in inputString)

【讨论】:

"isupper 检查密码中的所有字符是否都是大写"。否:`"HELLO WORLD !!".isupper()` 产生True。它检查是否至少有一个大写字母并且没有小写字母。【参考方案2】: isdigit() checks the whole string is a digit,如果字符串 包含 一个数字,则不是

如果字符串中的所有字符都是数字并且至少有一个字符,则返回true,否则返回false。

isupper() checks the whole string is in uppercase,如果字符串 包含 至少一个大写字符,则不会。

如果字符串中的所有大小写字符都是大写并且至少有一个大小写字符,则返回 true,否则返回 false。

你需要的是使用any built-in function:

如果password 中至少存在一位数字,any([x.isdigit() for x in password]) 将返回 True 如果至少一个字符被视为大写,any([x.isupper() for x in password]) 将返回 True。

【讨论】:

【参考方案3】:

也许你可以使用正则表达式:

re.search(r"[A-Z]", password)

检查大写字母。

re.search(r"[0-9]", password)

检查密码中的数字。

【讨论】:

【参考方案4】:

您可以将re 模块用于正则表达式。

使用它,您的代码将如下所示:

import re

def validate():
    while True:
        password = raw_input("Enter a password: ")
        if len(password) < 8:
            print("Make sure your password is at lest 8 letters")
        elif re.search('[0-9]',password) is None:
            print("Make sure your password has a number in it")
        elif re.search('[A-Z]',password) is None: 
            print("Make sure your password has a capital letter in it")
        else:
            print("Your password seems fine")
            break

validate()

【讨论】:

【参考方案5】:
r_p = re.compile('^(?=\S6,20$)(?=.*?\d)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[^A-Za-z\s0-9])')

此代码将使用以下代码验证您的密码:

    最小长度为6,最大长度为20 至少包含一个数字, 至少一个大写字母和一个小写字母 至少一个特殊字符

【讨论】:

【参考方案6】:

您正在检查整个密码字符串对象的 isdigit 和 isupper 方法,而不是字符串的每个字符。以下是检查密码是否符合您的特定要求的功能。它不使用任何正则表达式的东西。它还会打印输入密码的所有缺陷。

#!/usr/bin/python3
def passwd_check(passwd):
    """Check if the password is valid.

    This function checks the following conditions
    if its length is greater than 6 and less than 8
    if it has at least one uppercase letter
    if it has at least one lowercase letter
    if it has at least one numeral
    if it has any of the required special symbols
    """
    SpecialSym=['$','@','#']
    return_val=True
    if len(passwd) < 6:
        print('the length of password should be at least 6 char long')
        return_val=False
    if len(passwd) > 8:
        print('the length of password should be not be greater than 8')
        return_val=False
    if not any(char.isdigit() for char in passwd):
        print('the password should have at least one numeral')
        return_val=False
    if not any(char.isupper() for char in passwd):
        print('the password should have at least one uppercase letter')
        return_val=False
    if not any(char.islower() for char in passwd):
        print('the password should have at least one lowercase letter')
        return_val=False
    if not any(char in SpecialSym for char in passwd):
        print('the password should have at least one of the symbols $@#')
        return_val=False
    if return_val:
        print('Ok')
    return return_val

print(passwd_check.__doc__)
passwd = input('enter the password : ')
print(passwd_check(passwd))

【讨论】:

使用return_val 是非pythonic。如果无效则返回 False,如果有效则返回 True。【参考方案7】:

或者你可以用它来检查它是否至少有一个数字:

min(passwd).isdigit()

【讨论】:

max(passwd).isupper() 根本不起作用,只有在特殊情况下才起作用【参考方案8】:

Python 2.7 for 循环将为每个字符分配一个条件编号。即列表中的 Pa$$w0rd = 1,2,4,4,2,3,2,2,5。由于集合仅包含唯一值,因此集合 = 1,2,3,4,5;因此,由于满足所有条件,集合的 len = 5。如果是 pa$$w,则集合 = 2,4,len = 2 因此无效

name = raw_input("Enter a Password: ")
list_pass=set()
special_char=['#','$','@']
for i in name:
    if(i.isupper()):
      list_pass.add('1')
  elif (i.islower()):
      list_pass.add('2')
  elif(i.isdigit()) :
      list_pass.add('3')
  elif(i in special_char):
      list_pass.add('4')
if len(name) >=6 and len(name) <=12:
    list_pass.add('5')
if len(list_pass) is 5:
    print ("Password valid")
else: print("Password invalid")

【讨论】:

不鼓励仅使用代码的答案。为了帮助未来的读者,请解释一下你在做什么!【参考方案9】:
''' Minimum length is 5;
 - Maximum length is 10;
 - Should contain at least one number;
 - Should contain at least one special character (such as &, +, @, $, #, %, etc.);
 - Should not contain spaces.
'''

import string

def checkPassword(inputStr):
    if not len(inputStr):
        print("Empty string was entered!")
        exit(0)

    else:
        print("Input:","\"",inputStr,"\"")

    if len(inputStr) < 5 or len(inputStr) > 10:
        return False

    countLetters = 0
    countDigits = 0
    countSpec = 0
    countWS = 0

    for i in inputStr:
        if i in string.ascii_uppercase or i in string.ascii_lowercase:
             countLetters += 1
        if i in string.digits:
            countDigits += 1
        if i in string.punctuation:
            countSpec += 1
        if i in string.whitespace:
            countWS += 1

    if not countLetters:
        return False
    elif not countDigits:
        return False
    elif not countSpec:
        return False
    elif countWS:
        return False
    else:
        return True


print("Output: ",checkPassword(input()))

使用正则表达式

s = input("INPUT: ")
print("\n".format(s, 5 <= len(s) <= 10 and any(l in "0123456789" for l in s) and any(l in "!\"#$%&'()*+,-./:;<=>?@[\]^_`|~" for l in s) and not " " in s))

模块导入

from string import digits, punctuation

def validate_password(p):
    if not 5 <= len(p) <= 10:
        return False

    if not any(c in digits for c in p):
        return False

    if not any(c in punctuation for c in p):
        return False

    if ' ' in p:
        return False

    return True

for p in ('DJjkdklkl', 'John Doe'
, '$kldfjfd9'):
    print(p, ': ', ('invalid', 'valid')[validate_password(p)], sep='')

【讨论】:

【参考方案10】:

例子:

class Password:
    def __init__(self, password):
        self.password = password

    def validate(self):        
        vals = 
        'Password must contain an uppercase letter.': lambda s: any(x.isupper() for x in s),
        'Password must contain a lowercase letter.': lambda s: any(x.islower() for x in s),
        'Password must contain a digit.': lambda s: any(x.isdigit() for x in s),
        'Password must be at least 8 characters.': lambda s: len(s) >= 8,
        'Password cannot contain white spaces.': lambda s: not any(x.isspace() for x in s)            
         
        valid = True  
        for n, val in vals.items():                         
           if not val(self.password):                   
               valid = False
               return n
        return valid                

    def compare(self, password2):
        if self.password == password2:
            return True


if __name__ == '__main__':
    input_password = input('Insert Password: ')
    input_password2 = input('Repeat Password: ')
    p = Password(input_password)
    if p.validate() is True:
        if p.compare(input_password2) is True:
            print('OK')
    else:
       print(p.validate())

【讨论】:

【参考方案11】:
uppercase_letter = ['A', 'B','C', 'D','E','F','G','H','I','J','K','L','M','N','O',
            'P','Q','R','S','T','U','V','W','X','Y','Z']

number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

import re

info =

while True:

    user_name = input('write your username: ')

    if len(user_name) > 15:
        print('username is too long(must be less than 16 character)')
    elif len(user_name) < 3 :
        print('username is short(must be more than 2 character)')
    else:
        print('your username is', user_name)
        break


while True:   

    password= input('write your password: ')

    if len(password) < 8 :
        print('password is short(must be more than 7 character)')

    elif len(password) > 20:
        print('password is too long(must be less than 21 character)') 

    elif re.search(str(uppercase_letter), password ) is None :
        print('Make sure your password has at least one uppercase letter in it')

    elif re.search(str(number), password) is None :
        print('Make sure your password has at least number in it')

    else:
        print('your password is', password)
        break

info['user name'] = user_name

info['password'] = password

print(info)

【讨论】:

您能解释一下您的代码如何以及为什么回答这些问题吗? @mike 首先,如果您认为我的代码有用,请点击向上箭头 :),而且我的代码也是可读的,如果您有问题,请告诉我 :) 【参考方案12】:

当然,使用正则表达式有更简单的答案,但这是最简单的方法之一

from string import punctuation as p
s = 'Vishwasrocks@23' #or user input is welcome
lis = [0, 0, 0, 0]
for i in s:
    if i.isupper():
        lis[0] = 1
    elif i.islower():
        lis[1] = 1
    elif i in p:
        lis[2] = 1
    elif i.isdigit():
        lis[3] = 1
print('Valid') if 0 not in lis and len(s) > 8 else print('Invalid')

【讨论】:

【参考方案13】:

使用普通方法的最简单的python验证

password = '-'

while True:
    password = input(' enter the passwword : ')
    lenght = len(password)

    while lenght < 6:
        password = input('invalid , so type again : ')

        if len(password)>6:
            break

    while not any(ele.isnumeric() for ele in password):
        password = input('invalid , so type again : ')
    while not any(ele.isupper() for ele in password):
        password = input('invalid , so type again : ')
    while not any(ele not in "[@_!#$%^&*()<>?/|~:]" for ele in password):
        password = input('invalid , so type again : ')
    break

【讨论】:

以上是关于验证密码 - Python的主要内容,如果未能解决你的问题,请参考以下文章

验证密码 - Python

案例:python实现名字汉字验证,密码验证

python快速生成验证码(密码)

在python中识别密码验证中的特殊字符

密码验证合格程序(Python)

python--学习--用户名和密码验证