|
| 1 | +''' |
| 2 | +Created on Jan 27, 2023 |
| 3 | +@author: dnichol |
| 4 | +Bulk update users email addresses from CSV. CSV file requires two columns, titled 'Existing' and 'New'. This script is case sensitive. |
| 5 | +''' |
| 6 | + |
| 7 | +import csv |
| 8 | +import logging |
| 9 | +import argparse |
| 10 | +import sys |
| 11 | +import json |
| 12 | +import traceback |
| 13 | +from requests import HTTPError, RequestException |
| 14 | + |
| 15 | +from blackduck import Client |
| 16 | + |
| 17 | +def log_config(): |
| 18 | + # TODO: debug option in .restconfig file to be reflected |
| 19 | + logging.basicConfig(format='%(asctime)s:%(levelname)s:%(module)s: %(message)s', stream=sys.stderr, level=logging.DEBUG) |
| 20 | + logging.getLogger("requests").setLevel(logging.WARNING) |
| 21 | + logging.getLogger("urllib3").setLevel(logging.WARNING) |
| 22 | + logging.getLogger("blackduck").setLevel(logging.WARNING) |
| 23 | + |
| 24 | +def parse_parameter(): |
| 25 | + parser = argparse.ArgumentParser("Bulk update users from CSV file - modifies the email addresses of the users given the existing email and new email address") |
| 26 | + parser.add_argument("CSV", help="Location of the CSV file") |
| 27 | + # "CSV File requires two columns titled 'Existing' and 'New'", |
| 28 | + return parser.parse_args() |
| 29 | + |
| 30 | +def get_user_by_email(hub_client, email): |
| 31 | + params = { |
| 32 | + 'q': [f"name:{email}"] |
| 33 | + } |
| 34 | + for user in hub_client.get_items("/api/users", params=params): |
| 35 | + if user['email'] == email: |
| 36 | + user_url = hub_client.list_resources(user)['href'] |
| 37 | + print(f"Found user: {email}") |
| 38 | + return user |
| 39 | + |
| 40 | + |
| 41 | +def read_csv(hub_client, csv_path): |
| 42 | + updated = 0 |
| 43 | + failed = 0 |
| 44 | + not_found = 0 |
| 45 | + with open(csv_path, newline='') as csvfile: |
| 46 | + reader = csv.DictReader(csvfile) |
| 47 | + for row in reader: |
| 48 | + existing_email = (row['Existing']) |
| 49 | + new_email = (row['New']) |
| 50 | + try: |
| 51 | + user = get_user_by_email(hub_client, existing_email) |
| 52 | + if user: |
| 53 | + update_user(hub_client, existing_email, new_email, user) |
| 54 | + updated += 1 |
| 55 | + else: |
| 56 | + logging.info(f"User {existing_email} was not found") |
| 57 | + not_found += 1 |
| 58 | + except RequestException as err: |
| 59 | + logging.error(f"Failed to update user {existing_email}. Reason is " + str(err)) |
| 60 | + failed += 1 |
| 61 | + except Exception as err: |
| 62 | + raise err |
| 63 | + |
| 64 | + logging.info(f"------------------------------") |
| 65 | + logging.info(f"Execution complete.") |
| 66 | + logging.info(f"{updated} users updated") |
| 67 | + logging.info(f"{not_found} users were not found") |
| 68 | + logging.info(f"{failed} users failed to update") |
| 69 | + |
| 70 | +def update_user(hub_client, existing_email, new_email, user): |
| 71 | + user_url = hub_client.list_resources(user)['href'] |
| 72 | + |
| 73 | + # Update the email address. |
| 74 | + user['email'] = new_email |
| 75 | + |
| 76 | + # Not just update the email address. If the email is also used as userName and externalUserName then update them too. |
| 77 | + if user['userName'] == existing_email: |
| 78 | + user['userName'] = new_email |
| 79 | + if user.get('externalUserName') and user['externalUserName'] == existing_email: |
| 80 | + user['externalUserName'] = new_email |
| 81 | + |
| 82 | + logging.info(f"Updating user {existing_email} to {user['email']} for user {user_url}s") |
| 83 | + hub_client.session.put(user_url, json=user) |
| 84 | + |
| 85 | + |
| 86 | +def main(): |
| 87 | + log_config() |
| 88 | + args = parse_parameter() |
| 89 | + try: |
| 90 | + with open('.restconfig.json','r') as f: |
| 91 | + config = json.load(f) |
| 92 | + hub_client = Client(token=config['api_token'], |
| 93 | + base_url=config['baseurl'], |
| 94 | + verify=not config['insecure'], |
| 95 | + timeout=15, |
| 96 | + retries=3) |
| 97 | + |
| 98 | + read_csv(hub_client, args.CSV) |
| 99 | + except HTTPError as err: |
| 100 | + hub_client.http_error_handler(err) |
| 101 | + except Exception as err: |
| 102 | + logging.error(f"Failed to perform the task. See the stack trace") |
| 103 | + traceback.print_exc() |
| 104 | + |
| 105 | +if __name__ == '__main__': |
| 106 | + sys.exit(main()) |
| 107 | + |
0 commit comments