2013-05-23 10 views
5

Sto provando a creare un sistema che richiede l'inserimento di una password. Se è tutto inferiore, superiore o num, stampa debole, se è due delle condizioni, allora è med e se tutti sono stati soddisfatti è forte. Semplicemente non sembra funzionare.Controllo della potenza di una password (come controllare le condizioni)

Il lavoro debole e forte, tuttavia il mezzo non lo fa.

Non so dove ho sbagliato.

def password(): 

    print ('enter password') 
    print() 
    print() 
    print ('the password must be at least 6, and no more than 12 characters long') 
    print() 

    password = input ('type your password ....') 


    weak = 'weak' 
    med = 'medium' 
    strong = 'strong' 

    if len(password) >12: 
     print ('password is too long It must be between 6 and 12 characters') 

    elif len(password) <6: 
     print ('password is too short It must be between 6 and 12 characters') 


    elif len(password) >=6 and len(password) <= 12: 
     print ('password ok') 

     if password.lower()== password or password.upper()==password or password.isalnum()==password: 
      print ('password is', weak) 

     elif password.lower()== password and password.upper()==password or password.isalnum()==password: 
      print ('password is', med) 

     else: 
      password.lower()== password and password.upper()==password and password.isalnum()==password 
      print ('password is', strong) 
+1

afaik isalnum() restituisce un valore booleano in modo non è mai sta per essere uguale a una password – pypat

risposta

4

password.isalnum() restituisce un valore booleano, quindi password.isalnum()==password sarà sempre essere False.

basta omettere la parte ==password:

if password.lower()== password or password.upper()==password or password.isalnum(): 
    # ... 

successivo, può mai essere sia tutto superiore e inferiore, o tutti superiore e numeri o tutti inferiore e tutti i numeri, in modo che la seconda condizione (media) è impossibile. Forse dovresti cercare la presenza di di alcune maiuscole, minuscole e cifre?

Tuttavia, in primo luogo un altro problema da affrontare. Stai verificando se la password è alfanumerico, costituita da soli caratteri e/o numeri. Se vuoi testare solo numeri, usa .isdigit().

È possibile acquisire familiarità con lo string methods. Ci sono a portata di mano .islower() e .isupper() metodi disponibili che si potrebbe desiderare di provare, ad esempio:

>>> 'abc'.islower() 
True 
>>> 'abc123'.islower() 
True 
>>> 'Abc123'.islower() 
False 
>>> 'ABC'.isupper() 
True 
>>> 'ABC123'.isupper() 
True 
>>> 'Abc123'.isupper() 
False 

Questi sono più veloci e meno prolissa che l'utilizzo password.upper() == password, il seguente metterà alla prova lo stesso:

if password.isupper() or password.islower() or password.isdigit(): 
    # very weak indeed 

Il trucco successivo che si desidera imparare è il loop su una stringa, quindi è possibile testare i singoli caratteri:

>>> [c.isdigit() for c in 'abc123'] 
[False, False, False, True, True, True] 

I f si combinano con la funzione any(), è possibile verificare se ci sono alcuni personaggi che sono i numeri:

>>> any(c.isdigit() for c in 'abc123') 
True 
>>> any(c.isdigit() for c in 'abc') 
False 

Penso che troverete quei trucchi a portata di mano durante il test per i punti di forza di password.

2

Ecco un remake di quello che hai scritto:

import re 

def password(): 
    print ('Enter a password\n\nThe password must be between 6 and 12 characters.\n') 

    while True: 
     password = input('Password: ... ') 
     if 6 <= len(password) < 12: 
      break 
     print ('The password must be between 6 and 12 characters.\n') 

    password_scores = {0:'Horrible', 1:'Weak', 2:'Medium', 3:'Strong'} 
    password_strength = dict.fromkeys(['has_upper', 'has_lower', 'has_num'], False) 
    if re.search(r'[A-Z]', password): 
     password_strength['has_upper'] = True 
    if re.search(r'[a-z]', password): 
     password_strength['has_lower'] = True 
    if re.search(r'[0-9]', password): 
     password_strength['has_num'] = True 

    score = len([b for b in password_strength.values() if b]) 

    print ('Password is %s' % password_scores[score]) 

uscita (campione):

>>> password() 
Enter a password 

The password must be between 6 and 12 characters. 

Password: ... ghgG234 
Password is Strong 
+0

sto lavorando con Python 3 – user2412839

+0

Passa 'raw_input' a' input' e siete pronti per partire, e viceversa se si utilizza python 2. (Ho già modificato la mia risposta, quindi dovrebbe andare bene) –

1

Sono stato anche alla ricerca di un po 'di sicurezza della password funzione di esaminare, e ha trovato molti mezzo lavorata suggerimento. Ho assemblato la mia funzione basandomi su quelle.

speranza di aiutare

def get_pw_strength(pw): 

    s_lc = set(['a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', 'k', 'j', 'm', 'l', 'o', 'n', 'q', 'p', 's', 'r', 'u', 't', 'w', 'v', 'y', 'x', 'z']) 
    s_uc = set(['A', 'C', 'B', 'E', 'D', 'G', 'F', 'I', 'H', 'K', 'J', 'M', 'L', 'O', 'N', 'Q', 'P', 'S', 'R', 'U', 'T', 'W', 'V', 'Y', 'X', 'Z']) 
    s_dg = set(['1', '0', '3', '2', '5', '4', '7', '6', '9', '8']) 
    s_sp = set(['+', ',', '.', '-', '?', ':', '_', '(', ')', '*', '/', ';', '+', '!']) 
    pw_s = 0 
    pw_steps = (5, 8, 12) 

    pw_l = len(pw) 
    if (pw_l < 4): 
     return 0 
    for l in pw_steps : 
     if (pw_l > l): 
      pw_s += 1 
      #print "length over ", l," giving point", pw_s 

    c_lc = c_uc = c_dg = c_sp = 0 
    for c in pw : 
     if (c in s_lc) : 
      c_lc += 1 
     if (c in s_uc) : 
      c_uc += 1 
     if (c in s_dg) : 
      c_dg += 1 
     if (c in s_sp) : 
      c_sp += 1 
    if (c_lc + c_uc + c_dg + c_sp <> pw_l): 
     #print c_lc, c_uc, c_dg, c_sp, pw_l 
     #raise Exception "Forbidden chracter" 
     return -1 
    charset = 0 
    if (c_lc) : 
     pw_s += 1 
     charset = len(s_lc) 
    if (c_uc) : 
     pw_s += 1 
     charset = len(s_uc) 
    if (c_dg) : 
     pw_s += 1 
     charset = len(s_dg) 
    if (c_sp) : 
     pw_s += 2 
     charset = len(s_sp) 
    entropy = log(pow(charset,pw_l),2) 

    return pw_s, entropy 
12

Holá
L'approccio migliore è utilizzare ricerca di espressioni regolari
Qui è la funzione Attualmente sto usando

def password_check(password): 
    """ 
    Verify the strength of 'password' 
    Returns a dict indicating the wrong criteria 
    A password is considered strong if: 
     8 characters length or more 
     1 digit or more 
     1 symbol or more 
     1 uppercase letter or more 
     1 lowercase letter or more 
    """ 

    # calculating the length 
    length_error = len(password) < 8 

    # searching for digits 
    digit_error = re.search(r"\d", password) is None 

    # searching for uppercase 
    uppercase_error = re.search(r"[A-Z]", password) is None 

    # searching for lowercase 
    lowercase_error = re.search(r"[a-z]", password) is None 

    # searching for symbols 
    symbol_error = re.search(r"[ !#$%&'()*+,-./[\\\]^_`{|}~"+r'"]', password) is None 

    # overall result 
    password_ok = not (length_error or digit_error or uppercase_error or lowercase_error or symbol_error) 

    return { 
     'password_ok' : password_ok, 
     'length_error' : length_error, 
     'digit_error' : digit_error, 
     'uppercase_error' : uppercase_error, 
     'lowercase_error' : lowercase_error, 
     'symbol_error' : symbol_error, 
    } 

EDIT:
Arresto dell'impianto un suggerimento di Lukasz qui è un aggiornamento della verifica delle condizioni speciali simbolo

symbol_error = re.search(r"\W", password) is None 
+0

Per il symbol_error esiste un modo per usare '\ W * \ s'? Elencare i simboli non sembra efficiente. Ad esempio l'elenco che ci ometti?, <, > e molti altri. – Lukasz

+0

Grazie per il tuo commento Lukasz. La ricerca di simboli potrebbe essere semplificata con l'uso della sequenza speciale \ W. Non è necessario includere \ s perché lo spazio è già incluso in \ W. Pertanto, il codice per "cercare i simboli" deve essere modificato in: symbol_error = re.search (r "\ W", password) è Nessuno – ePi272314

Problemi correlati