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: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools