# -*- coding: utf-8 -*- import os import shutil import sqlite3 class PasswordManager: PASSWORD_FILE="/net/server-sync/var/lib/n4d/n4d.sqlite" LOG_PATH="/net/server-sync/var/lib/n4d" def __init__(self): self.create_database() #def init def create_database(self): if not os.path.exists(PasswordManager.PASSWORD_FILE): if not os.path.exists(PasswordManager.LOG_PATH): os.makedirs(PasswordManager.LOG_PATH) conn = sqlite3.connect(PasswordManager.PASSWORD_FILE) cursor = conn.cursor() cursor.execute('create table password (cn text, sn text, uid text, passwd text)') conn.commit() cursor.close() conn.close() prevmask = os.umask(0) os.chmod(PasswordManager.PASSWORD_FILE,0640) os.umask(prevmask) try: conn = sqlite3.connect(PasswordManager.PASSWORD_FILE) cursor = conn.cursor() cursor.execute('select cn,sn,uid,passwd from password') result = cursor.fetchall() cursor.close() conn.close() except: os.remove(PasswordManager.PASSWORD_FILE) self.create_database() def add_password(self,user_name,cn,sn,password): self.create_database() conn = sqlite3.connect(PasswordManager.PASSWORD_FILE) cursor = conn.cursor() cursor.execute('select * from password where uid = "'+user_name+'"') result = cursor.fetchall() if len(result) > 0 : # user on database cursor.execute('update password set passwd = "'+password+'" where uid = "'+user_name+'"' ) else: cursor.execute('insert into password (cn,sn,uid,passwd) values ("'+cn+'","'+sn+'","'+user_name+'","'+password+'")') conn.commit() cursor.close() conn.close() #def add_password def remove_password(self,user_name): self.create_database() conn = sqlite3.connect(PasswordManager.PASSWORD_FILE) cursor = conn.cursor() cursor.execute('delete from password where uid = "'+user_name+'"') conn.commit() cursor.close() conn.close() #def remove_password def get_passwords(self): self.create_database() list = [] conn = sqlite3.connect(PasswordManager.PASSWORD_FILE) cursor = conn.cursor() cursor.execute('select cn,sn,uid,passwd from password') result = cursor.fetchall() for user in result : a = {} a['cn'] = user[0].encode('utf-8') a['sn'] = user[1].encode('utf-8') a['uid'] = user[2] a['passwd'] = user[3] list.append(a) conn.close() return list #def get_passwords def is_user_in_database(self,uid): for user in self.get_passwords(): if user["uid"]==uid: return [True,user] return [False,""] #def is_user_in_database def set_externally_modified(self,uid): ret,user=self.is_user_in_database(uid) if ret: self.add_password(user["uid"],user["cn"],user["sn"],"#! CHANGED MANUALLY !#") #def set_externally_modified #class PasswordManager if __name__=="__main__": pm=PasswordManager() pm.add_password("test","password2") pm.add_password("test2","password2") pm.remove_password("raul")