利用python来写一个用户管理系统
注意:代码要用到数据库,数据库用户为‘postfix‘,数据库名为‘test’,表结构为‘username,password,last_login’
环境配置代码:
1.yum install mariadb-server.x86_64 MySQL-python.x86_64 -y
2.systemctl start mariadb
注意:代码要用到数据库,数据库用户为‘postfix‘,数据库名为‘test’,表结构为‘username,password,last_login’
环境配置代码:
1.yum install mariadb-server.x86_64 MySQL-python.x86_64 -y
2.systemctl start mariadb
#!/usr/bin/env python
# coding:utf-8
import getpass
import time
import MySQLdb
cxn = MySQLdb.connect(user = 'postfix')
cur = cxn.cursor()
cur.execute("use test")
def test(lastTime,nowTime):
lastTime = str(lastTime)
year = int(lastTime[0:4])
month = int(lastTime[5:7])
day = int(lastTime[8:10])
hour = int(lastTime[11:13])
if nowTime.tm_year == year and nowTime.tm_mon == month and nowTime.tm_mday == day and nowTime.tm_hour - hour <= 4:
return True
else:
return False
def menu():
print "================================"
print "\t(D)elete a user"
print "\t(A)dd a user"
print "\t(L)ogin system"
print "\t(S)how system"
print "\tEnter a different exit"
print "================================"
return raw_input(">>>")
def delete():
username = raw_input("Please input username to delete:")
cur.execute("DELETE FROM users WHERE username = '%s'"%(username))
cxn.commit()
print "successful!"
def add():
username = raw_input("Please input username to addition:")
password = getpass.getpass("Please input password:")
Time = time.localtime()
now_time = "%d-%d-%d %d:%d:%d"%(Time.tm_year,Time.tm_mon,Time.tm_mday,Time.tm_hour,Time.tm_min,Time.tm_sec)
cur.execute("INSERT INTO users VALUES ('%s', '%s', '%s')"%(username,password,now_time))
cxn.commit()
print "successful!"
def login():
for i in range(3):
username = raw_input("Please input username:")
password = getpass.getpass("Please input password:")
cur.execute("select * from users where username='%s'"%(username))
data = cur.fetchone()
if isinstance(data,tuple) and password == data[1]:
print "login successful!"
Time = time.localtime()
now_time = "%d-%d-%d %d:%d:%d"%(Time.tm_year,Time.tm_mon,Time.tm_mday,Time.tm_hour,Time.tm_min,Time.tm_sec)
if test(data[2],Time):
print "You already logged in at:%s"%(data[2])
else:
print "last login:%s"%data[2]
cur.execute("UPDATE users SET last_login = '%s' WHERE username = '%s'"%(now_time,data[0]))
cxn.commit()
break
else :
print "ERROR:username not exist or password error"
print "You have %d chance"%(2-i)
def show():
cur.execute("SELECT * FROM users")
for data in cur.fetchall():
print "%s\t%s\t%s"%data
while 1:
key = menu()
if key == 'D' or key == 'd':
delete()
elif key == 'A' or key == 'a':
add()
elif key == 'L' or key == 'l':
login()
elif key == 'S' or key == 's':
show()
else:
print "THANKS"
cxn.close()
exit()