From c13c14cc2186e7e5a30ad6d8e38a1f26500f3bcf Mon Sep 17 00:00:00 2001 From: Imran Hussain <imranh@sucs.org> Date: Sun, 10 Mar 2019 12:17:04 +0000 Subject: [PATCH] Run code inspection tool against code, fix bugs and style --- sucsam.py | 181 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 93 insertions(+), 88 deletions(-) diff --git a/sucsam.py b/sucsam.py index b587758..e118269 100644 --- a/sucsam.py +++ b/sucsam.py @@ -12,13 +12,14 @@ from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import ldap + def correctPaidUntilStr(): - #same logic as suapi stuff + # same logic as suapi stuff # if it's greater than Sept then year+1 # if it's less than Spet then year - if (month >= 9): - paidyear = year +1 - elif (month < 8): + if month >= 9: + paidyear = year + 1 + elif month < 8: paidyear = year else: print("Something went really wrong") @@ -35,9 +36,9 @@ def stripFuturePeople(listofpeeps): badpeeps.append(person) else: paidyeararray = person[1].split(' ') - if (month >= 9): + if month >= 9: paidyear = year + 1 - elif (month < 8): + elif month < 8: paidyear = year else: print("Something went really wrong") @@ -46,6 +47,7 @@ def stripFuturePeople(listofpeeps): badpeeps.append(person) return badpeeps + # ok this needs explaning # in comes a list [('user1', 'Sept. 2015'), ('user2', 'Sept. 2014')] # we need to work out what account type it is, @@ -62,12 +64,11 @@ def sendReminderEmail(listofpeeps): username = DBdata[0][1] realname = DBdata[0][2] email = DBdata[0][3] - type = DBdata[0][7] + acctype = DBdata[0][7] adminname = pwd.getpwuid(os.geteuid())[0] - if os.path.isfile(str(type)+"-email"): - #file = open(str(type)+"-email","r") - file = codecs.open(str(type)+"-email", encoding='utf-8') + if os.path.isfile(str(acctype) + "-email"): + file = codecs.open(str(acctype) + "-email", encoding='utf-8') data = file.read() file.close() data = data.replace("{$realname}",realname) @@ -88,12 +89,13 @@ def sendReminderEmail(listofpeeps): smtpConn = smtplib.SMTP('localhost') smtpConn.sendmail(sender, receiver, message.as_string()) smtpConn.quit() - if debugmode > 0: #only send out one email instead of 85464684164864165 + if debugmode > 0: # only send out one email instead of 85464684164864165 sys.exit(0) else: print("Renewal email template not found!") sys.exit(4) + def mainMenu(): print("\nPlease choose an option") print("[h] Diplay some help") @@ -106,22 +108,22 @@ def mainMenu(): option = input("Option: ") print("\n") - if (option == "h"): + if option == "h": print("help text comming soon") mainMenu() - elif (option == "q"): + elif option == "q": DBconn.close() sys.exit(0) - elif (option == "qs"): + elif option == "qs": quickStats() mainMenu() - elif (option == "la"): + elif option == "la": listUsers() mainMenu() - elif (option == "r"): + elif option == "r": reminderMenu() mainMenu() - elif (option == "d"): + elif option == "d": deleteAccounts() mainMenu() else: @@ -170,9 +172,9 @@ def listUsers(): def emailDeletedUser(userDBinfo): - username = userDBdata[0][1] - realname = userDBdata[0][2] - email = userDBdata[0][3] + username = userDBinfo[0][1] + realname = userDBinfo[0][2] + email = userDBinfo[0][3] adminname = pwd.getpwuid(os.geteuid())[0] file = codecs.open("deleted-email", encoding='utf-8') @@ -204,11 +206,11 @@ def emailAdminDeleteUser(username): data = data.replace("{$username}",username) data = data.replace("{$adminname}",adminname) sender = 'staff@sucs.org' - receiver = email + receiver = "logs@sucs.org" message = MIMEMultipart() message['From'] = sender - message['To'] = "logs@sucs.org" - message['Subject'] = username +'\'s SUCS account has been deleted' + message['To'] = receiver + message['Subject'] = username + '\'s SUCS account has been deleted' messageBody = MIMEText(data, 'plain', "UTF-8") message.attach(messageBody) @@ -219,85 +221,85 @@ def emailAdminDeleteUser(username): def deleteUser(peopleList): - #get fs ready + # get fs ready basedir = "/home/deleted" mboxdir = "/var/mail/" - subprocess.call(['sudo', 'mkdir', "-m", "700", directory]) + subprocess.call(['sudo', 'mkdir', "-m", "700", basedir]) for person in peopleList: - #get all their info from the db + # get all their info from the db cur = DBconn.cursor() cur.execute("SELECT * from members WHERE username=%(user)s",{"user" : person[0]}) userDBinfo = cur.fetchall() cur.close() - #get all their info from the ldap + # get all their info from the ldap userLDAPinfo = ldapconn.search_s(ldap_base,ldap.SCOPE_SUBTREE,"uid="+str(person[0])) - #declare some easy to use vars + # declare some easy to use vars username = str(person[0]) persondir = basedir+"/"+username - #make the dir to store their stuff + # make the dir to store their stuff subprocess.call(["sudo", "mkdir", persondir]) - #kill all their procs + # kill all their procs subprocess.call(["sudo", "pkill", "-u", username]) - #backup their ldap entry - #sudo ldapsearch -x -D "cn=Manager,dc=sucs,dc=org" -y /etc/ldap.secret "(uid=imranh)" + # backup their ldap entry + # sudo ldapsearch -x -D "cn=Manager,dc=sucs,dc=org" -y /etc/ldap.secret "(uid=imranh)" ldapbackupfile = open("./ldap-ldif", "w") subprocess.call(["sudo", "ldapsearch", "-x", "-D", ldap_manager, "-y", ldap_manager_pass, "-L", "(uid="+username+")"], stdout=ldapbackupfile) ldapbackupfile.close() subprocess.call(['sudo', 'mv', "-f", "./ldap-ldif", persondir+"/ldap-ldif"]) - #delete them from ldap - #ldapconn.delete_s(ldap_base,ldap.SCOPE_SUBTREE,"uid="+str(person[0])) - #sudo ldapdelete -D "cn=Manager,dc=sucs,dc=org" -y /etc/ldap.secret "uid=imran,ou=people,dc=sucs,dc=org" + # delete them from ldap + # ldapconn.delete_s(ldap_base,ldap.SCOPE_SUBTREE,"uid="+str(person[0])) + # sudo ldapdelete -D "cn=Manager,dc=sucs,dc=org" -y /etc/ldap.secret "uid=imran,ou=people,dc=sucs,dc=org" subprocess.call(["sudo", "ldapdelete", "-D", ldap_manager, "-y", ldap_manager_pass, userLDAPinfo[0][0]]) - #move their homedir to the deleted folder + # move their homedir to the deleted folder subprocess.call(['sudo', 'mv', "-f", userLDAPinfo[0][1]["homeDirectory"][0], persondir+"/homedir"]) - #move their mail to the deleted folder + # move their mail to the deleted folder subprocess.call(['sudo', 'mv', "-f", mboxdir+username, persondir+"/mbox"]) - #remove them from the printer - #pkusers --delete imranh + # remove them from the printer + # pkusers --delete imranh subprocess.call(['sudo', 'pkusers', "--delete", username]) - #remove from mailing lists - #/usr/lib/mailman/bin/remove_members members imranh@sucs.org - #/usr/lib/mailman/bin/remove_members users imranh@sucs.org - subprocess.call(['sudo', '/usr/lib/mailman/bin/remove_members', "members", userLDAPinfo[0][1]["mail"][0]]) #sucs email - subprocess.call(['sudo', '/usr/lib/mailman/bin/remove_members', "members", userDBinfo[0][3]]) #main email - subprocess.call(['sudo', '/usr/lib/mailman/bin/remove_members', "members", userDBinfo[0][6]+"@swan.ac.uk"]) # iss email - subprocess.call(['sudo', '/usr/lib/mailman/bin/remove_members', "users", userLDAPinfo[0][1]["mail"][0]]) #sucs email - subprocess.call(['sudo', '/usr/lib/mailman/bin/remove_members', "users", userDBinfo[0][3]]) #main email - subprocess.call(['sudo', '/usr/lib/mailman/bin/remove_members', "users", userDBinfo[0][6]+"@swan.ac.uk"]) # iss email - - #time to delete them from the db :( + # remove from mailing lists + # /usr/lib/mailman/bin/remove_members members imranh@sucs.org + # /usr/lib/mailman/bin/remove_members users imranh@sucs.org + subprocess.call(['sudo', '/usr/lib/mailman/bin/remove_members', "members", userLDAPinfo[0][1]["mail"][0]]) # sucs email + subprocess.call(['sudo', '/usr/lib/mailman/bin/remove_members', "members", userDBinfo[0][3]]) # main email + subprocess.call(['sudo', '/usr/lib/mailman/bin/remove_members', "members", userDBinfo[0][6]+"@swan.ac.uk"]) # iss email + subprocess.call(['sudo', '/usr/lib/mailman/bin/remove_members', "users", userLDAPinfo[0][1]["mail"][0]]) # sucs email + subprocess.call(['sudo', '/usr/lib/mailman/bin/remove_members', "users", userDBinfo[0][3]]) # main email + subprocess.call(['sudo', '/usr/lib/mailman/bin/remove_members', "users", userDBinfo[0][6]+"@swan.ac.uk"]) # iss email + + # time to delete them from the db :( cur = DBconn.cursor() - #delete from doorcards first + # delete from doorcards first cur.execute("DELETE FROM doorcards WHERE uid=%(uid)s",{"uid" : userDBinfo[0][0]}) - #delete from members table + # delete from members table cur.execute("DELETE FROM members WHERE username=%(user)s",{"user" : person[0]}) - #add their some details to the oldmembers table + # add their some details to the oldmembers table cur.execute("INSERT into oldmembers (username,realname) VALUES (%(user)s,%(realname)s)",{"user" : username,"realname" : userDBinfo[0][2]}) DBconn.commit() cur.close() - #notify people - #them + # notify people + # them emailDeletedUser(userDBinfo) - #logs@ + # logs@ emailAdminDeleteUser(person[0]) - #remove the entry from the list - peoplelist.remove(person) + # remove the entry from the list + peopleList.remove(person) - #return to the deletemenu with an empty list as we've just deleted everyone - deleteMenu(peoplelist) + # return to the deletemenu with an empty list as we've just deleted everyone + deleteMenu(peopleList) def reminderMenu(): @@ -311,24 +313,25 @@ def reminderMenu(): option = input("Option: ") - if (option == "1"): + if option == "1": for student in studentsBad: - print(str(student[0]) + " because the DB says: " + str(student[1]) ) + print(str(student[0]) + " because the DB says: " + str(student[1])) for soc in societiesBad: - print(str(soc[0]) + " because the DB says: " + str(soc[1]) ) + print(str(soc[0]) + " because the DB says: " + str(soc[1])) for ass in associatesBad: - print(str(ass[0]) + " because the DB says: " + str(ass[1]) ) + print(str(ass[0]) + " because the DB says: " + str(ass[1])) reminderMenu() - if (option == "2"): + if option == "2": sendReminderEmail(studentsBad) sendReminderEmail(societiesBad) sendReminderEmail(associatesBad) - if (option == "2.1"): + if option == "2.1": sendReminderEmail(studentsBad) - if (option == "0"): + if option == "0": mainMenu() else: - reminderMenu() + reminderMenu() + def deleteMenu(deleteArray): print("") @@ -341,15 +344,15 @@ def deleteMenu(deleteArray): option = input("Option: ") - if (option == "1"): + if option == "1": print("\nThe following users will be deleted: ") for user in deleteArray: print(user) deleteMenu(deleteArray) - elif (option == "2"): + elif option == "2": print("Enter a username to add or remoeve it from the list.") user = input("Username: ") - if (user in deleteArray): + if user in deleteArray: deleteArray.remove(user) print(str(user) + " won't be deleted.") else: @@ -360,39 +363,41 @@ def deleteMenu(deleteArray): except KeyError: print("\x1b[1;31mInvalid user.\x1b[0m") deleteMenu(deleteArray) - elif (option == "3"): + elif option == "3": for student in studentsBad: - print("Adding " + str(student[0]) + " to the list because the DB says: " + str(student[1]) ) + print("Adding " + str(student[0]) + " to the list because the DB says: " + str(student[1])) deleteArray.append(student[0]) for soc in societiesBad: - print("Adding " + str(soc[0]) + " to the list because the DB says: " + str(soc[1]) ) + print("Adding " + str(soc[0]) + " to the list because the DB says: " + str(soc[1])) deleteArray.append(soc[0]) for ass in associatesBad: - print("Adding " + str(ass[0]) + " to the list because the DB says: " + str(ass[1]) ) + print("Adding " + str(ass[0]) + " to the list because the DB says: " + str(ass[1])) deleteArray.append(ass[0]) deleteMenu(deleteArray) - elif (option == "3.1"): + elif option == "3.1": for student in studentsBad: - print("Adding " + str(student[0]) + " to the list because the DB says: " + str(student[1]) ) + print("Adding " + str(student[0]) + " to the list because the DB says: " + str(student[1])) deleteArray.append(student[0]) - elif (option == "9"): + elif option == "9": print("Nope not yet") deleteMenu(deleteArray) - elif (option == "0"): + elif option == "0": mainMenu() else: deleteMenu(deleteArray) + def deleteAccounts(): - #list that store usernames to be deleted - #gets reset everytime you go into this bit on purpose + # list that store usernames to be deleted + # gets reset everytime you go into this bit on purpose tobedeleted = [] deleteMenu(tobedeleted) ### MAIN ### -if (os.geteuid() == 0): + +if os.geteuid() == 0: print("\x1b[1;31mDon't run this as root!\x1b[0m") sys.exit(1) @@ -401,21 +406,21 @@ now = datetime.datetime.now() year = now.year month = now.month -#This tool was written for python *3* -#but doesn't mean we can't support 2 as well :) +# This tool was written for python *3* +# but doesn't mean we can't support 2 as well :) try: input = raw_input except NameError: pass -#try and connect to the db +# try and connect to the db try: DBconn = psycopg2.connect(database="sucs") except: print("Can't connect to the SUCS DB, suiciding!") sys.exit(2) -#try and connect to ldap +# try and connect to ldap try: ldapconn = ldap.initialize("ldap://sucs.org") ldapconn.simple_bind_s("","") @@ -426,7 +431,7 @@ except: print("Can't connect to the SUCS LDAP, suiciding") sys.exit(2) -#store some data from to db to operate on +# store some data from to db to operate on cur = DBconn.cursor() cur.execute("SELECT username,paid from members WHERE type=1 ORDER BY paid") @@ -446,4 +451,4 @@ hons = cur.fetchall() cur.close() print("\x1b[33mWelcome to the SUCS Account Manager!\x1b[0m") -mainMenu() \ No newline at end of file +mainMenu() -- GitLab