[sysadmin-bin] Migrate these scripts to py3



commit 43080a6545582bb190a0fe71c46c387b46667751
Author: Andrea Veri <averi redhat com>
Date:   Thu Nov 12 18:57:11 2020 +0100

    Migrate these scripts to py3

 cleanup-inactive-ldap-accounts.py   | 24 +++++++++++-------------
 gitlab/gitlab-operations.py         | 28 ++++++++++++++--------------
 membership/foundation-operations.py | 14 +++++++-------
 reset-my-password.py                | 23 +++++++++++------------
 4 files changed, 43 insertions(+), 46 deletions(-)
---
diff --git a/cleanup-inactive-ldap-accounts.py b/cleanup-inactive-ldap-accounts.py
index af66034..ddd6da2 100755
--- a/cleanup-inactive-ldap-accounts.py
+++ b/cleanup-inactive-ldap-accounts.py
@@ -1,6 +1,5 @@
-#!/usr/bin/python
+#!/usr/bin/python3
 
-from __future__ import print_function
 import calendar
 import datetime
 import hashlib
@@ -13,7 +12,7 @@ import time
 from optparse import OptionParser
 from email.MIMEText import MIMEText
 
-from gnome_ldap_utils import *
+import gnome_ldap_utils as Glu
 import gitlab
 
 
@@ -24,9 +23,8 @@ def get_disk_path(project_id):
     path = os.path.join(repo_path, hashed[0:2], hashed[2:4], hashed)
     return "{}.git".format(path)
 
-
-execfile('/home/admin/secret/freeipa_rw_ftpadmin_gnomecvs')
-execfile('/home/admin/secret/gitlab_rw')
+exec(open('/home/admin/secret/freeipa_rw_ftpadmin_gnomecvs').read())
+exec(open('/home/admin/secret/gitlab_rw').read())
 
 parser = OptionParser()
 parser.add_option("--print-inactive-accounts", action="store_true", default=False,
@@ -38,7 +36,7 @@ parser.add_option("--verbose",
 (options, args) = parser.parse_args()
 
 if socket.gethostname() != 'gitlab.gnome.org':
-    print ("You are not allowed to run this script on a different host than gitlab.gnome.org, exiting...", 
end='\n')
+    print("You are not allowed to run this script on a different host than gitlab.gnome.org, exiting...", 
end='\n')
     sys.exit(1)
 
 glu = Gnome_ldap_utils(LDAP_GROUP_BASE, LDAP_HOST, LDAP_USER_BASE, LDAP_USER, LDAP_PASSWORD)
@@ -72,7 +70,7 @@ for user, last_pushed in last_pushed_times.iteritems():
     if last_pushed < now - 2 * 365 * 24 * 60 * 60:
         last_pushed = time.gmtime(last_pushed)
         if options.print_inactive_accounts:
-            print ("%s: %s" % (user, time.strftime("%d-%m-%Y", last_pushed)), end='\n')
+            print (f"{ user }: { time.strftime('%d-%m-%Y', last_pushed)) }", end='\n')
 
 
 def user_is_current(username):
@@ -96,15 +94,15 @@ def add_remove_comment_to_user(username, group):
 
         glu.add_or_update_description(username, comment, update=True)
 
-    form_letter = """
-Hello %s, your membership of the group %s has been automatically removed, due to inactivity.
+    form_letter = f"""
+Hello { name }, your membership of the group { group } has been automatically removed, due to inactivity.
 
 For more information, please see the following email:
 https://mail.gnome.org/archives/foundation-list/2014-March/msg00063.html
 
 With cordiality,
 
-the GNOME Accounts Team""" % (name, group)
+the GNOME Accounts Team"""
 
     try:
         msg = MIMEText(form_letter)
@@ -131,7 +129,7 @@ ftpadmin_users = (glu.get_uids_from_group('ftpadmin', excludes))
 for gnomecvs_user in gnomecvs_users:
     if not user_is_current(gnomecvs_user):
         if options.verbose:
-            print ("Removing user %s from gnomecvs" % gnomecvs_user, end='\n')
+            print(f"Removing user { gnomecvs_user } from gnomecvs", end='\n')
 
         glu.remove_user_from_ldap_group(gnomecvs_user, 'gnomecvs')
         add_remove_comment_to_user(gnomecvs_user, 'gnomecvs')
@@ -139,7 +137,7 @@ for gnomecvs_user in gnomecvs_users:
 for ftpadmin_user in ftpadmin_users:
     if not user_is_current(ftpadmin_user):
         if options.verbose:
-            print ("Removing user %s from ftpadmin" % ftpadmin_user, end='\n')
+            print("Removing user { ftpadmin_user } from ftpadmin", end='\n')
 
         glu.remove_user_from_ldap_group(ftpadmin_user, 'ftpadmin')
         add_remove_comment_to_user(gnomecvs_user, 'ftpadmin')
diff --git a/gitlab/gitlab-operations.py b/gitlab/gitlab-operations.py
index f87652e..76d6e5b 100755
--- a/gitlab/gitlab-operations.py
+++ b/gitlab/gitlab-operations.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/python3
 
 import sys
 import gitlab
@@ -6,15 +6,15 @@ import re
 
 sys.path.append('/home/admin/bin')
 sys.path.append('/home/admin/bin/git')
-import gnome_ldap_utils
+import gnome_ldap_utils as Glu
 import semi_rdf
 
 from xml.sax import SAXParseException
 
-execfile('/home/admin/secret/freeipa_ro')
-execfile('/home/admin/secret/gitlab_rw')
+exec(open("/home/admin/secret/freeipa_ro").read())
+exec(open("/home/admin/secret/gitlab_rw").read())
 
-glu = gnome_ldap_utils.Gnome_ldap_utils(LDAP_GROUP_BASE, LDAP_HOST, LDAP_USER_BASE, LDAP_USER, LDAP_PASSWORD)
+glu = Glu.Gnome_ldap_utils(LDAP_GROUP_BASE, LDAP_HOST, LDAP_USER_BASE, LDAP_USER, LDAP_PASSWORD)
 gl = gitlab.Gitlab('https://gitlab.gnome.org', GITLAB_PRIVATE_RW_TOKEN, api_version=4)
 
 DOAP = "http://usefulinc.com/ns/doap#";
@@ -50,7 +50,7 @@ for username, id in ldapusers_dict.iteritems():
         try:
             user.keys.create({'title': 'Imported from account.gnome.org', 'key': ssh_key})
 
-            print 'Key for username %s with id %i has been added' % (username, id)
+            print(f"Key for username { username } with id { id } has been added")
         except gitlab.exceptions.GitlabCreateError as e:
             if e.response_code == 400:
                 pass
@@ -64,7 +64,7 @@ for username, id in ldapusers_dict.iteritems():
                 group.members.create({'user_id': id,
                                       'access_level': gitlab.DEVELOPER_ACCESS})
 
-                print 'Username %s with id %i has been added to the GNOME group' % (username, id)
+                print(f"Username { username } with id { id } has been added to the GNOME group")
         except gitlab.exceptions.GitlabCreateError as e:
             if e.response_code == 409:
                 pass
@@ -74,7 +74,7 @@ for username, id in ldapusers_dict.iteritems():
                 l10n_group.members.create({'user_id': id,
                                            'access_level': gitlab.REPORTER_ACCESS})
 
-                print 'Username %s with id %i has been added to the Teams/Translation group' % (username, id)
+                print(f"Username { username } with id { id } has been added to the Teams/Translation group")
         except gitlab.exceptions.GitlabCreateError as e:
             if e.response_code == 409:
                 pass
@@ -86,10 +86,10 @@ for username, id in gnomeusers_dict.iteritems():
             pass
         else:
             group.members.delete(id)
-            print 'Username with id %i has been removed from the GNOME group' % id
+            print(f"Username { username } with id { id } has been removed from the GNOME group")
 
             l10n_group.members.delete(id)
-            print 'Username with id %i has been removed from the Teams/Translation group' % id
+            print(f"Username { username } with id { id } has been removed from the Teams/Translation group")
 
 maints = dict()
 for project in projects:
@@ -161,7 +161,7 @@ for project in maints:
                 proj.members.create({'user_id': userid, 'access_level':
                                      gitlab.MASTER_ACCESS})
 
-                print 'Landed master level access to %s against repository %s' % (user, project)
+                print(f"Landed master level access to { user } against repository { project }")
             except gitlab.exceptions.GitlabCreateError as e:
                 if e.response_code == 409:
                     member = proj.members.get(userid)
@@ -170,7 +170,7 @@ for project in maints:
                         proj.members.create({'user_id': userid, 'access_level':
                                          gitlab.MASTER_ACCESS})
 
-                        print 'Landed master level access to %s against repository %s' % (user, project)
+                        print(f"Landed master level access to { user } against repository { project }") % 
(user, project)
 
     members = proj.members.list()
     members_dict = {}
@@ -197,10 +197,10 @@ for project in maints:
             if _member.attributes['access_level'] == 40:
                 proj.members.delete(members_dict[member])
 
-                print 'Dropped master level access to %s against repository %s as maintainer entry is 
missing on the DOAP file' % (member, project)
+                print(f"Dropped master level access to { member } against repository { project } as 
maintainer entry is missing on the DOAP file")
             elif _member.attributes['access_level'] == 20:
                 pass
             else:
                 proj.members.delete(members_dict[member])
 
-                print 'Dropped level access %s, this means user %s was added manually on project %s, that is 
not necessary as permissions are inherited from the GNOME group by default' % 
(_member.attributes['access_level'], member, project)
+                print(f"Dropped level access { _member.attributes['access_level'] }, this means user { 
member } was added manually on project { project }, that is not necessary as permissions are inherited from 
the GNOME group by default'
diff --git a/membership/foundation-operations.py b/membership/foundation-operations.py
index d483c88..b753aa2 100755
--- a/membership/foundation-operations.py
+++ b/membership/foundation-operations.py
@@ -11,7 +11,7 @@ from email.mime.text import MIMEText
 from optparse import OptionParser
 
 sys.path.append('/home/admin/bin')
-from gnome_ldap_utils import *
+import gnome_ldap_utils as Glu
 
 usage = "usage: %prog [options]"
 parser = OptionParser(usage)
@@ -44,7 +44,7 @@ if len(sys.argv) == 1:
     sys.exit(1)
 
 try:
-    execfile('/home/admin/secret/freeipa_rw_foundation')
+    exec(open('/home/admin/secret/freeipa_rw_foundation').read())
 except IOError as e:
     if e.errno == 2:
         LDAP_GROUP_BASE = os.environ.get('LDAP_GROUP_BASE')
@@ -54,10 +54,10 @@ except IOError as e:
         LDAP_PASSWORD = os.environ.get('LDAP_PASSWORD')
         LDAP_CA_PATH = os.environ.get('LDAP_CA_PATH')
 
-glu = Gnome_ldap_utils(LDAP_GROUP_BASE, LDAP_HOST, LDAP_USER_BASE, LDAP_USER, LDAP_PASSWORD)
+glu = Glu.Gnome_ldap_utils(LDAP_GROUP_BASE, LDAP_HOST, LDAP_USER_BASE, LDAP_USER, LDAP_PASSWORD)
 
 today = dt.date.today()
-foundationmembers = glu.get_uids_from_group('foundation')
+foundationmembers = Glu.get_uids_from_group('foundation')
 
 
 def send_renewal_emails():
@@ -104,7 +104,7 @@ def remove_expired_memberships_from_foundation():
         if today == (last_renewed_on + delta_2y - delta_1m):
            send_form_letters(close_to_expire_membership_form_letter, mail_attr, common_name_attr, 
last_renewed_on_attr)
         elif (today - delta_2y) == last_renewed_on:
-            print "Removing %s from the foundation LDAP group as the membership expired on %s" % (member, 
last_renewed_on_attr)
+            print(f"Removing { member } from the foundation LDAP group as the membership expired on { 
last_renewed_on_attr }")
             glu.remove_user_from_ldap_group(member, 'foundation')
             send_form_letters(expired_membership_form_letter, mail_attr, common_name_attr, 
last_renewed_on_attr)
 
@@ -165,9 +165,9 @@ def send_form_letters(form_letter, email, name, *args):
         server = smtplib.SMTP("localhost")
         server.sendmail(msg['From'], [msg['To'], msg['Cc']], msg.as_string())
         server.quit()
-        print "Successfully sent email to %s with email %s" % (name, email)
+        print(f"Successfully sent email to { name } with email { email }")
     except smtplib.SMTPException:
-        print "ERROR: I wasn't able to send the email correctly, please check /var/log/maillog!"
+        print("ERROR: I wasn't able to send the email correctly, please check /var/log/maillog!")
 
 
 def subscribe_new_members():
diff --git a/reset-my-password.py b/reset-my-password.py
index a1e0c98..23137d2 100755
--- a/reset-my-password.py
+++ b/reset-my-password.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/python3
 
 import string
 import smtplib
@@ -6,12 +6,11 @@ import sys
 import os
 
 from email.MIMEText import MIMEText
-from gnome_ldap_utils import *
+import gnome_ldap_utils as Glu
 
-execfile('/home/admin/secret/freeipa_rw_resets')
-
-glu = Gnome_ldap_utils(LDAP_GROUP_BASE, LDAP_HOST, LDAP_USER_BASE, LDAP_USER, LDAP_PASSWORD)
+exec(open('/home/admin/secret/freeipa_rw_resets').read())
 
+glu = Glu.Gnome_ldap_utils(LDAP_GROUP_BASE, LDAP_HOST, LDAP_USER_BASE, LDAP_USER, LDAP_PASSWORD)
 
 def gen_passwd(length=12, chars=string.letters + string.digits):
     urandom = open("/dev/urandom")
@@ -42,11 +41,11 @@ def check_existing_password(userid):
     sysadminteam =  glu.get_group_from_ldap('sysadmin')
 
     if glu.get_attributes_from_ldap(userid, 'uid') == None:
-       print 'The specified UID does not exist, please get in contact with the GNOME Accounts Team to know 
more'
+       print('The specified UID does not exist, please get in contact with the GNOME Accounts Team to know 
more')
        sys.exit(1)
 
     if userid in (accountsteam or sysadminteam):
-       print 'You are not allowed to reset your password, please contact the GNOME Sysadmin Team to know why'
+       print('You are not allowed to reset your password, please contact the GNOME Sysadmin Team to know 
why')
        sys.exit(1)
 
     update_password(userid)
@@ -64,10 +63,10 @@ def update_password(userid):
 
 
 def send_password_to_user(name, email, password):
-    form_letter = """
-Hello %s, your password has been reset successfully. Your temporary password is
+    form_letter = f"""
+Hello { name }, your password has been reset successfully. Your temporary password is
 
-%s
+{ password }
 
 Please login at https://account.gnome.org and update your password within the next couple
 of hours (the password cannot be changed instantly as the reset that was just performed
@@ -86,9 +85,9 @@ the GNOME Accounts Team""" % (name, password)
         server = smtplib.SMTP("localhost")
         server.sendmail(msg['From'], msg['To'], msg.as_string())
         server.quit()
-        print "Successfully sent your password to the registered email address being %s" % (email)
+        print(f"Successfully sent your password to the registered email address being { email }")
     except smtplib.SMTPException:
-        print "ERROR: I wasn't able to send the email correctly, please check /var/log/maillog!"
+        print("ERROR: I wasn't able to send the email correctly, please check /var/log/maillog!")
 
 my_userid = os.getenv('SUDO_USER')
 check_existing_password(my_userid)


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]