Implement simple user management system with Python

Source: Internet
Author: User

"Python core programming" seventh of the exercises fifth question

One: Topic Description:

userpw2.py. The following questions and example 7.1 of the management name-password key value of the data program.

(a) Modify the script so that he can record the user's last login date and time (using the Times module) and save it with the user's password. The interface of the program requires the user to enter a user name and password prompt. Whether the user name is successful, should be prompted, after the user login successful, should update the corresponding user's last login timestamp. If the time difference between this login and the last login is not more than four hours, then notify the user: "You already in at:<last_login_timestamp>".

(b) Add a Management menu with the following two items: (1) Delete a user (2) displays the names of all the users in the system and their password list.

(c) The password is not currently encrypted. Please add a code for password encryption

(d) Add a graphical interface to the program, for example, with Tkinter. (Graphical interface development is more complex, it is not used here.) )

(e) require that the user name cloth be case-sensitive.

(f) Enforce restrictions on user names, and do not allow symbols and whitespace characters.

(g) Merge two options for "New user" and "old user". If a new user tries to log in with a nonexistent user name, ask if the user is a new user, and if yes, create the user. Otherwise, according to the old user's way to log in.

Two:

The modules used in the program are explained as follows:

(1) Re: Regular expression engine, method for calling regular expressions in Python

(2) Pickle: Object persistence, writing data to disk

(3) DateTime: Time processing for recording user login timestamp

(4) BASE64:BASE64 encryption module

(5) Hashlib:hash encryption module

Full code:

#-*-coding:utf-8-*-#2017.7.17 Import re import pickle import base64,hashlib from datetime import datetime D EF initialization (file_name): ' ' ' program initialization, creating User.ini and Time.ini Files ' ' dict_test={' admin ': ' db69fc039dcbd2962cb4d28f58 91aae1 '} #创建超级管理员, the default password is admin f = file (file_name, ' A + ') #以追加的方式打开文件, to avoid files being modified if Len (F.readlines ()) ==0: #判断程序是否              is empty, initialize the If file_name== ' User.ini ': Pickle.dump (Dict_test, F, True) else only at the first run: Pickle.dump ({},f, True) f.close () def encodepass (passwd): "" with Base64 and MD5 double-layer encryption, the crack may be almost 0 "m = HASHL IB.MD5 () pwd = Base64.b64encode (passwd) m.update (PWD) return m.hexdigest () def time_order (user): "          "Log User login time, results saved in Time.ini file" ft = File (' Time.ini ', ' r ') DBT = pickle.load (ft) if user not in DBT: Dbt.setdefault (User,datetime.today ()) Else:time_value = Dbt[user] t = datetime.today ()-time_valu         E Try:     If T.hour<=4:print ' already logged in at:<last_login_timestamp> ' except: print ' You already logged in at:<last_login_timestamp> ' dbt[user] = datetime.today () ft = fil E (' Time.ini ', ' W ') Pickle.dump (DBT, FT, True) ft.close () def newuser (db): "User-created program, tuned by Olduser with "While true:name = raw_input (' Please input the username: ') if Re.match (R ' \w ', name): #采用正则表达 Check whether the user name is legal pass Else:print ' Username should be made of a~z, A~z, 0~9, _ ' Con          Tinue for ValueName in Db.keys (): if name.lower () = = Valuename.lower (): Break        Else:break passwd = raw_input (' Please input the password: ') db[name] = Encodepass (passwd) def olduser (db): ' User login program ' ' name = Raw_input (' Login: ') if name in db:pwd = Raw_input (' Pass WD: ') passwd =Db.get (name) if passwd = = Encodepass (PWD): print ' Welcome back! ', name Time_order (name)      Else:print ' Login incorrent! ' Else:yn = Raw_input (' Do-want to instead a new user? Yes or No: ') if yn.lower () = = ' Yes ': newuser (db) print ' \ n ', Def deluser (db): " ' Delete a user, but must be an administrator ' ' print ' please login as admin ' #管理员的身份才能删除用户 name = Raw_input (' login: ') pwd = raw_in Put (' passwd: ') passwd = db.get (name) if passwd = = Encodepass (pwd) and name== ' admin ': User = Raw_input (' Please input a user name: ') if user! = ' admin ': if Db.pop (user): print ' Delete Curr          Ent! '      Else:print ' Con not delete admin! '  Else:print ' wrong PASSWPRD ' def checkuser (db): "" View all users, but must be the administrator's identity ' print ' please login as Admin ' #管理员的身份才能查看所有用户 name = Raw_input (' Login: ') pwd = Raw_inpUT (' passwd: ') passwd = db.get (name) if passwd = = Encodepass (pwd) and name = = ' Admin ': for key in DB:  print ' username:%10s ====> password:%10s '% (Key,db[key]) Else:print ' Can not check all    Users! ' def resetuser (db): "' Change password, but must enter old password correctly" ' name = raw_input (' Please input the username: ') passwd = raw_in Put (' Please input old password: ') if db[name] = = Encodepass (passwd): passwd = raw_input (' "Please input new PA    ssWOrd: ') db[name] = Encodepass (passwd) else:print ' wrong password! ' Def showmenu (): "The main function of the program run" FU = file (' User.ini ', ' r ') db = Pickle.load (fu) prompt = "" (L) Ogin          Now (Q) uit (D) Elet User (C) Heck all user (R) eset Password Enter choice: "' done = False and not" done: chosen = False while not chosen:try:choice = Raw_input (Prompt). Split () [0]. Lower () except (Eoferror,Keyboardinterrupt): choice = ' q ' print ' \nyou picked:[%s] '% choice if choice n                                OT in ' LQDCR ': print ' invalid option,try again ' Else:chosen = True if choice = = ' Q ':d one = True if choice = = ' L ': olduser (db) if choice = = ' d ':d elus ER (db) if choice = = ' C ': CheckUser (db) if choice = = ' R ': Resetuser (db) fu = file (' User.ini ' , ' W ') Pickle.dump (db,fu,true) fu.close () if __name__ = = ' __main__ ': ' "The system has a user named Admi n Password for admin Super User, please change password now!      ' Print ' Welcome to User information Management system! ' Initialization (' User.ini ') initialization (' Time.ini ') ShowMenu ()

Implement simple user management system with Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.