Найти - Пользователи
Полная версия: выход из цикла
Начало » Python для новичков » выход из цикла
1 2 3 4 5
ffrr
Пр запуске такого скрипта:
 #!/usr/bin/env python3.8
                                                                          
import getpass                          
import pymysql
import hashlib                       
import uuid                                            
import re
import time                             
import pyinputplus as pyip
import os
from uuid import getnode as mac
                                                                                          
t = 4                                                                  
                                             
print("-------------------------")   
print("<<<<<<<<<Welcome>>>>>>>>>")                           
print("-------------------------")
print("Please enter a username (after 3 unlucky attempts system will reboot)")
while True:                                                               
        t -= 1                                             
        if t > 0:                            
                     
                username = pyip.inputNum('Username (must be 12 numbers): ', min=111111111111, max=999999999999, limit=3)
                                
                db = pymysql.connect("hostname","user","pass","db")
       
                # prepare a cursor object using cursor() method
                cursor = db.cursor()          
                cursor.execute("SELECT userID, password from permissions")                                              
                data = cursor.fetchone()                                                                                
                                                                                                                        
                dbuser, dbpass = data                                                                                   
                #dbuser, dbpass = str(data[0]), data[1]                                                                 
                                                                                                                        
                # disconnect from server                                                                                
                db.close()                                                                                              
                                                                                                                        
                if username == dbuser :                                                                         
                        while True:                                                                                     
                                password = getpass.getpass(prompt="Enter secret password:")                     
                                                                                                                        
                                if (hashlib.sha1(password.encode()).hexdigest() == dbpass):                             
                                        print("Authentication success")                                                 
                                        break                                                                           
                                else:                                                                                   
                                        print("Bad password")                                                           
                                                                                                                        
                                t -= 1                                                                                  
                                if t > 0:                                                                               
                                        print('Left attempts=>', t)                                                     
                                else:                                                                                   
                                        print('System will reboot now...')                                              
                                        time.sleep(3)                                                                   
        #                               os.system("reboot")                                                             
                                        break                                                                           
                else:                                                                                                   
                        print ("please try another username. This username is incorrect")                               
                        continue                                                           
                break                                                                      

не срабатывает лимит limit=3 на ввод username и скрипт просто подвисает после 3-х неудачных ввода username:
  # ./auth.py 
-------------------------
<<<<<<<<<Welcome>>>>>>>>>
-------------------------
Please enter a username (after 3 unlucky attempts system will reboot)
Username (must be 12 numbers): 659605758502
please try another username. This username is incorrect
Username (must be 12 numbers): 659605758503
please try another username. This username is incorrect
Username (must be 12 numbers): 659605758505
please try another username. This username is incorrect
FishHook
 while True:       # 1                                                        
        t -= 1           # 2                                  
        if t > 0:      # 3
              # bla-bla              

Вот как вы думаете, что будет выполнять ваша программа, если на шаге 3 переменная t окажется меньше нуля?
ffrr
наверное подвиснет)). Нужен в конце еще блок else: ? Так он вроде присутствует у меня…
AD0DE412
ffrr
Так он вроде присутствует у меня…
неа
ffrr
где здесь еще не хватает else?
                 if username == dbuser :                                                                         
                        while True:                                                                                     
                                password = getpass.getpass(prompt="Enter secret password:")                     
                                                                                                                        
                                if (hashlib.sha1(password.encode()).hexdigest() == dbpass):                             
                                        print("Authentication success")                                                 
                                        break                                                                           
                                else:                                                                                   
                                        print("Bad password")                                                           
                                                                                                                        
                                t -= 1                                                                                  
                                if t > 0:                                                                               
                                        print('Left attempts=>', t)                                                     
                                else:                                                                                   
                                        print('System will reboot now...')                                              
                                        time.sleep(3)                                                                   
        #                               os.system("reboot")                                                             
                                        break                                                                           
                else:                                                                                                   
                        print ("please try another username. This username is incorrect")                               
                        continue                                                           
                break                                                                      
AD0DE412
ffrr
и что из этого следует? у меня так указано:
                 else:                                                                                                   
                        print ("please try another username. This username is incorrect")                               
                        continue                                                                                        
                break 

неверная конструкция?
AD0DE412
это не считая что второе if t > 0: не понятно для чего
AD0DE412
 #!/usr/bin/env python3.8
import getpass                          
import pymysql
import hashlib                       
import uuid                                            
import re
import time                             
import pyinputplus as pyip
import os
from uuid import getnode as mac
t = 4                                                                  
print("-------------------------")   
print("<<<<<<<<<Welcome>>>>>>>>>")                           
print("-------------------------")
print("Please enter a username (after 3 unlucky attempts system will reboot)")
while True:                                                               
    t -= 1                                             
    if t > 0:                            
        username = pyip.inputNum('Username (must be 12 numbers): ', min=111111111111, max=999999999999, limit=3)
        db = pymysql.connect("hostname","user","pass","db")
        # prepare a cursor object using cursor() method
        cursor = db.cursor()          
        cursor.execute("SELECT userID, password from permissions")                                              
        data = cursor.fetchone()                                                                                
        dbuser, dbpass = data                                                                                   
        #dbuser, dbpass = str(data[0]), data[1]                                                                 
        # disconnect from server                                                                                
        db.close()                                                                                              
        if username == dbuser :                                                                         
            while True:                                                                                     
                password = getpass.getpass(prompt="Enter secret password:")                     
                if (hashlib.sha1(password.encode()).hexdigest() == dbpass):                             
                    print("Authentication success")                                                 
                    break                                                                           
                else:                                                                                   
                    print("Bad password")                                                           
                t -= 1                                                                                  
                if t > 0:                                                                               
                    print('Left attempts=>', t)                                                     
                else:                                                                                   
                    print('System will reboot now...')                                              
                    time.sleep(3)                                                                   
                    #os.system("reboot")                                                             
                    break                                                                           
        else:                                                                                                   
            print ("please try another username. This username is incorrect")                               
            continue                                                           
        break
    else:
        print('вот здеся обработка первого if')
зы хорошим советом будет избегать таких портянок разбивайте на функции иначе можно легко запутаться
ffrr
AD0DE412
это не считая что второе if t > 0: не понятно для чего
для того, чтобы и username и пароль спрашивало по 3 раза, дальше выполнялся бы reboot машины…
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB