import os import os.path import shutil import ldap import subprocess import pwd import multiprocessing class NetShareOperations: USER_DIRS=["Music","Videos","Pictures","Documents","Share","Groups"] LOG_FILE="/var/log/n4d/fileoperations" STUDENTS_FOLDER="/net/server-sync/home/students/" NET_TMP="/net/.tmp/" def __init__(self): if not os.path.exists(NetShareOperations.NET_TMP): os.mkdir(NetShareOperations.NET_TMP) #def init def send_file_to_group(self,group,orig_path,dest_folder="Desktop"): p = subprocess.Popen(["llxcfg-showvars","LDAP_BASE_DN"],stdout=subprocess.PIPE) output = p.communicate()[0] if output != "": basedn = output.split("'")[1] connect_ldap = ldap.initialize('ldap://server') connect_ldap.PORT = 636 ldap_result = connect_ldap.search_s("ou=Managed,ou=Group,"+basedn,ldap.SCOPE_SUBTREE,'cn='+group) try: ret=ldap_result[0][1] if ret.has_key("memberUid"): tmp=orig_path.split("/") file_name=tmp[len(tmp)-1] shutil.copy(orig_path,NetShareOperations.NET_TMP+file_name) for item in ret["memberUid"]: try: student_folder=NetShareOperations.STUDENTS_FOLDER+item+"/"+dest_folder+"/" src=NetShareOperations.NET_TMP+file_name dst=student_folder+file_name user_uid=pwd.getpwnam(item)[2] user_gid=pwd.getpwnam(item)[3] queue=multiprocessing.Queue() p=multiprocessing.Process(target=self.copy_file_as_user,args=(src,dst,user_uid,user_gid,True,queue)) p.start() p.join() ret=queue.get() if ret!=True: self.log("send_file_to_group",e,"copying from net to student folder multiprocess" + item) return False except Exception as e: self.log("send_file_to_group",e,"copying from net to student folder " + item) return False os.remove(NetShareOperations.NET_TMP+file_name) return True except Exception as e: self.log("send_file_to_group",e,group + " " + orig_path + " " + dest_folder) try: os.remove(NetShareOperations.NET_TMP+file_name) except: pass return False else: return False #def send_file_to_group def copy_file_as_user(self,src,dst,uid,gid,delete,queue): try: os.setgid(gid) os.setuid(uid) shutil.copy(src,dst) queue.put(True) except Exception as e: queue.put(e) #def copy_file_as_user def delete_dir_content(self,dir,net_share_safe=False): try: for item in os.listdir(dir): if os.path.isfile(dir+item): os.remove(dir+item) elif os.path.isdir(dir+item): if net_share_safe: if item not in NetShareOperations.USER_DIRS: shutil.rmtree(dir+item) else: self.delete_dir_content(dir+item+"/",net_share_safe) else: shutil.rmtree(dir+item) except Exception as e: print(e) self.log("delete_dir_content",e,dir + item) def log(self,function_name,exception,comment=None): try: f=open(NetShareOperations.LOG_FILE,"a") f.write("* When calling " + function_name + " something happened...\n\t") f.write(str(exception)) f.write("\n") if comment!=None: f.write("\tCoder Hint: " + str(comment)) f.write("\n") f.close() except: pass #def log if __name__=="__main__": nso=NetShareOperations() nso.send_file_to_group("4ESOA","asd") nso.send_file_to_group("asdddd","asd")