Home Backend Development Python Tutorial python从入门到精通(DAY 3)

python从入门到精通(DAY 3)

Jun 10, 2016 pm 03:06 PM
Getting started with python

要求:编写登陆接口

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

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

帐号文件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()                          #关闭帐号文件

Copy after login

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

代码如下:

#_*_ 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()
Copy after login

Statement of this Website
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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

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 does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

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 are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

See all articles