search
HomeBackend DevelopmentPython Tutorialpython从入门到精通(DAY 3)

要求:编写登陆接口

输入用户名密码
认证成功后显示欢迎信息
输错三次后锁定

针对此实例写了有二种类型的脚本,略有不同,具体如下:

帐号文件account.txt内容如下:

sam 123

david 12
kevin 123
lin 12
tailen 123
jack 12

锁文件account_lock.txt默认为空

一、只针对帐号文件里的用户进行判断并锁定,针对用户和密码各有三次错误重试机会。

1、流程图如下:

代码如下:

#!/usr/bin/python27
#_*_ coding:utf-8 _*_

import sys,os,getpass

os.system('clear')
i = 0
while i < 3:                            #只要用户登录异常不超过3次就不断循环
  name = raw_input("请输入用户名:")

  lock_file = open('account_lock.txt','r+')            #当用户输入用户名后,打开LOCK 文件 以检查是否此用户已经LOCK了
  lock_list = lock_file.readlines()

  for lock_line in lock_list:                   #循环LOCK文件 
    lock_line = lock_line.strip('\n')              #去掉换行符
    if name == lock_line:                    #如果LOCK了就直接退出
      sys.exit('用户 %s 已经被锁定,退出' % name) 

  user_file = open('account.txt','r')               #打开帐号文件 
  user_list = user_file.readlines()                
  for user_line in user_list:                   #对帐号文件进行遍历
    (user,password) = user_line.strip('\n').split()       #分别获取帐号和密码信息
    if name == user:                      #如用户名正常匹配
      j = 0
      while j < 3:                      #只要用户密码异常不超过3次就不断循环
        passwd = getpass.getpass('请输入密码:')       #输入隐藏密码
        if passwd == password:               #密码正确,提示欢迎登录
          print('欢迎登录管理平台,用户%s' % name)    
          sys.exit(0)                   #正常退出
        else:
          print('用户 %s 密码错误,请重新输入,还有 %d 次机会' % (name,2 - j))
        j += 1                       #密码输入错误后,循环值增加1
      else:
        lock_file.write(name + '\n')            #密码输入三次错误后,将该用户追加到LOCK文件
        sys.exit('用户 %s 达到最大登录次数,将被锁定并退出' % name)
    else:
      pass                          #当用户没匹配时,跳过并继续循环
  else:
    print('用户 %s 不存在,请重新输入,还有 %d 次机会' % (name,2 - i))
  i += 1                             #当用户输入错误时,循环值增加1
else:
  sys.exit('用户 %s 不存在,退出' % name)              #用户输入三次错误后,异常退出
      
lock_file.close()                          #关闭LOCK文件
user_file.close()                          #关闭帐号文件

二、针对帐号文件里的不存在的用户也可以进行判断并锁定,针对用户和密码共有三次错误重试机会

代码如下:

#_*_ coding:utf-8 _*_

import sys,os,getpass

os.system('clear')

retry_limit = 3
retry_count = 0

account_file = 'account.txt'
lock_file = 'account_lock.txt'

while retry_count < retry_limit:                     #只要重试不超过3次就不断循环
  username = raw_input('\033[31;43mUsername:\033[0m')
  username = username.strip()
  lock_check = open(lock_file)                     #当用户输入用户名后,打开LOCK 文件 以检查是否此用户已经LOCK了

  for line in lock_check.readlines():                 #循环LOCK文件 
    if username == line.strip('\n'):                 #去掉换行符
      sys.exit('\033[35mUser %s is locked!!!\033[0m' % username)  #如果LOCK了就直接退出
  password = raw_input('\033[32;41mPassword:\033[0m')         #输入密码

  f = open(account_file,'r')                      #打开帐号文件 
  match_flag = False                          # 默认为Flase,如果用户match 上了,就设置为 True

  for line in f.readlines():                      
    user,passwd = line.strip('\n').split()              #去掉每行多余的\n并把这一行按空格分成两列,分别赋值为user,passwd两个变量
    if username == user and password == passwd:           #判断用户名和密码是否都相等
      print('hello, %s !!' % username)
      match_flag = True                       #相等就把循环外的match_flag变量改为了True
      break                             #然后就不用继续循环了,直接 跳出,因为已经match上了
  f.close()

  if match_flag == False:                       #如果match_flag还为False,代表上面的循环中跟本就没有match上用户名和密码,所以需要继续循环
    print('sorry,%s is unmatched' % username)
    retry_count += 1                         #计数器加1
  else:
    print('wlecome login my learning system!')
    break                              #用户成功登录,退出脚本

else:
  print("you account %s is locked!!!" % username)
  g = open(lock_file,'a')
  g.write(username)                          #被锁用户追加到用户锁文件
  g.write('\n')  
  g.close()

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Python: Is it Truly Interpreted? Debunking the MythsPython: Is it Truly Interpreted? Debunking the MythsMay 12, 2025 am 12:05 AM

Pythonisnotpurelyinterpreted;itusesahybridapproachofbytecodecompilationandruntimeinterpretation.1)Pythoncompilessourcecodeintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).2)Thisprocessallowsforrapiddevelopmentbutcanimpactperformance,req

Python concatenate lists with same elementPython concatenate lists with same elementMay 11, 2025 am 12:08 AM

ToconcatenatelistsinPythonwiththesameelements,use:1)the operatortokeepduplicates,2)asettoremoveduplicates,or3)listcomprehensionforcontroloverduplicates,eachmethodhasdifferentperformanceandorderimplications.

Interpreted vs Compiled Languages: Python's PlaceInterpreted vs Compiled Languages: Python's PlaceMay 11, 2025 am 12:07 AM

Pythonisaninterpretedlanguage,offeringeaseofuseandflexibilitybutfacingperformancelimitationsincriticalapplications.1)InterpretedlanguageslikePythonexecuteline-by-line,allowingimmediatefeedbackandrapidprototyping.2)CompiledlanguageslikeC/C transformt

For and While loops: when do you use each in python?For and While loops: when do you use each in python?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.