python模拟Linux shell登陆

本程序主要是实现对python装饰器的进一步利用, 执行的过程如下:

  1. 用户输入用户名密码
  2. open()读取用户文件,判断用户名密码,判断是否锁定
    • 如果用户登入错误次数等于2则代表已经被锁定,则执行下一次输入
    • 如果用户没有被锁定,但用户名密码错误,则提示用户名密码错误,并在文件内把登入错误计数加1,进入下一次输入
  3. 如果经过上面的判断,则直接进入login_index函数(shell函数)

用户列表文件


['charl', '123', 0]
["sb1","1233",1]
['sb2', '1231', 2]
['sb3','1232',0]

程序实现


#!/bin/python3
# -*- coding:utf-8 -*-
''' python login auth example  '''
#imports
import getpass,os
#functions
def lock_user(username):
    ''' username -> modify userlist file '''
    temp_str = ""
    with open("userlist.swp",'w') as file_write , open("userlist",'r') as file_read:
        for line in file_read:
            temp_list = eval(line)
            if temp_list[0] == username:
                temp_list[2] += 1
                temp_str += str(temp_list)+"\n"
                continue
            temp_str += line
        file_write.write(temp_str)
    os.rename("userlist.swp", "userlist")
def user_input():
    ''' input username&&password -> return username&&password '''
    username = input("username:")
    password = getpass.getpass("password:")
    return username,password
def check_user(username,password = '',type = 'check'):
    '''
        username,password,check -> return t||f #username password lock check
        username,password,lock -> return  t||f #username locked or not
    '''
    flag = False
    with open("userlist",'r') as file_read:
        for line in file_read:
            temp_list = eval(line)
            if type == 'check':    
                if username == temp_list[0] and password == temp_list[1] \
                and temp_list[2] < 2:
                    return True #user not locked and correct user and pass
            if type == 'lock':
                if username == temp_list[0] and temp_list[2] >= 2:
                    return True #user has been locked

        else:
            return False
#login decorator
def auth(func):
    def wrapper(*args,**kwargs):
        while True:
            username,password = user_input() #get input
            if check_user(username, password,type='check'): #juge username and password correct or not
                print("login success!")
                func(username) #shell function
            else:
                if check_user(username, password, type='lock'): #juge user locked or not
                    print("This account has been locked!")
                else:
                    lock_user(username) #lock count += 1
                    print("incorrect username or password!")
    return wrapper
#shell function
@auth
def login_index(username = ""):
    while True:
        command = input("%s>" %username) #ask input command
        if command == 'ls':
            print(
'''
bin   dev  home  lib64       media  opt   root  sbin  sys  usr
boot  etc  lib   lost+found  mnt    proc  run   srv   tmp  var
''')
        if command == 'exit': #exit shell
            print("byebye!")
            exit()
#main program
def main():
    login_index()

#program entry
if __name__ == '__main__':
    main()

Leave a Reply

Your email address will not be published. Required fields are marked *