Last active
July 13, 2026 05:40
-
-
Save shinsaka/64a1ab7fc7103d1273fe7b75c7851694 to your computer and use it in GitHub Desktop.
Amazon Connect ユーザー情報一括CSVエクスポート
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| """ | |
| Connectインスタンスのユーザーデータを一括ダウンロード | |
| 出力形式: 閲覧用の日本語ヘッダーCSV(Connectへの再インポート用途ではない) | |
| 注意: | |
| - list_users / describe_user は routing profile / security profile / hierarchy group を | |
| ID でしか返さないため、名前解決に describe_routing_profile / describe_security_profile / | |
| describe_user_hierarchy_group を別途呼び出している(同一IDはプロセス内キャッシュして再利用) | |
| - タグ列は "Key:Value" 形式(Connect管理画面のタグ入力仕様)を "|" 区切りで連結 | |
| - オーディオエンハンスメントは VoiceEnhancementConfigs[0] のみ参照(チャンネル別設定は考慮しない) | |
| - describe_user はユーザー単位でしか呼べないため ThreadPoolExecutor で並列化している | |
| """ | |
| import argparse | |
| import csv | |
| import os | |
| import sys | |
| import threading | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| from datetime import datetime | |
| import boto3 | |
| from botocore.config import Config | |
| CSV_HEADER = [ | |
| "ログイン", | |
| "名", | |
| "姓", | |
| "ルーティングプロファイル", | |
| "セキュリティプロファイル", | |
| "階層", | |
| "電話の種類", | |
| "デスクの電話番号", | |
| "タグ", | |
| "持続的接続", | |
| "オーディオエンハンスメント (なし/音声分離/ノイズ抑制)", | |
| ] | |
| PHONE_TYPE_MAP = {"SOFT_PHONE": "ソフトフォン", "DESK_PHONE": "デスクフォン"} | |
| AUDIO_ENHANCEMENT_MAP = { | |
| "VOICE_ISOLATION": "音声分離", | |
| "NOISE_SUPPRESSION": "ノイズ抑制", | |
| } | |
| HIERARCHY_LEVELS = ["LevelOne", "LevelTwo", "LevelThree", "LevelFour", "LevelFive"] | |
| class NameCache: | |
| """routing profile / security profile / hierarchy group のID→名前キャッシュ(スレッドセーフ)""" | |
| def __init__(self): | |
| self._cache = {} | |
| self._lock = threading.Lock() | |
| def get_or_fetch(self, key, fetch_fn): | |
| with self._lock: | |
| if key in self._cache: | |
| return self._cache[key] | |
| value = fetch_fn() | |
| with self._lock: | |
| self._cache[key] = value | |
| return value | |
| def make_client(region=None, max_attempts=10): | |
| config = Config(retries={"max_attempts": max_attempts, "mode": "adaptive"}) | |
| session = boto3.Session(region_name=region) if region else boto3.Session() | |
| return session.client("connect", config=config) | |
| def upload_to_s3(local_path, bucket, key, region=None): | |
| session = boto3.Session(region_name=region) if region else boto3.Session() | |
| s3_client = session.client("s3") | |
| s3_client.upload_file(local_path, bucket, key) | |
| def get_routing_profile_name(client, instance_id, cache, routing_profile_id): | |
| if not routing_profile_id: | |
| return "" | |
| return cache.get_or_fetch( | |
| routing_profile_id, | |
| lambda: client.describe_routing_profile( | |
| InstanceId=instance_id, RoutingProfileId=routing_profile_id | |
| )["RoutingProfile"]["Name"], | |
| ) | |
| def get_security_profile_name(client, instance_id, cache, security_profile_id): | |
| return cache.get_or_fetch( | |
| security_profile_id, | |
| lambda: client.describe_security_profile( | |
| InstanceId=instance_id, SecurityProfileId=security_profile_id | |
| )["SecurityProfile"]["SecurityProfileName"], | |
| ) | |
| def get_hierarchy_names(client, instance_id, cache, hierarchy_group_id): | |
| if not hierarchy_group_id: | |
| return "" | |
| def fetch(): | |
| path = client.describe_user_hierarchy_group( | |
| InstanceId=instance_id, HierarchyGroupId=hierarchy_group_id | |
| )["HierarchyGroup"]["HierarchyPath"] | |
| names = [path[level]["Name"] for level in HIERARCHY_LEVELS if level in path] | |
| return "/".join(names) | |
| return cache.get_or_fetch(hierarchy_group_id, fetch) | |
| def list_user_ids(client, instance_id, limit=0): | |
| paginator = client.get_paginator("list_users") | |
| user_ids = [] | |
| for page in paginator.paginate(InstanceId=instance_id): | |
| for summary in page["UserSummaryList"]: | |
| user_ids.append(summary["Id"]) | |
| if limit and len(user_ids) >= limit: | |
| return user_ids | |
| return user_ids | |
| def build_row(client, instance_id, user_id, rp_cache, sp_cache, hg_cache): | |
| user = client.describe_user(InstanceId=instance_id, UserId=user_id)["User"] | |
| identity = user.get("IdentityInfo", {}) | |
| phone = user.get("PhoneConfig", {}) | |
| voice_configs = user.get("VoiceEnhancementConfigs", []) | |
| voice_mode = voice_configs[0].get("VoiceEnhancementMode", "NONE") if voice_configs else "NONE" | |
| tags = user.get("Tags", {}) | |
| routing_profile_name = get_routing_profile_name( | |
| client, instance_id, rp_cache, user.get("RoutingProfileId") | |
| ) | |
| security_profile_names = "|".join( | |
| get_security_profile_name(client, instance_id, sp_cache, sp_id) | |
| for sp_id in user.get("SecurityProfileIds", []) | |
| ) | |
| hierarchy_names = get_hierarchy_names( | |
| client, instance_id, hg_cache, user.get("HierarchyGroupId") | |
| ) | |
| return [ | |
| user.get("Username", ""), | |
| identity.get("FirstName", ""), | |
| identity.get("LastName", ""), | |
| routing_profile_name, | |
| security_profile_names, | |
| hierarchy_names, | |
| PHONE_TYPE_MAP.get(phone.get("PhoneType"), ""), | |
| f"'{phone['DeskPhoneNumber']}" if phone.get("DeskPhoneNumber") else "", | |
| "|".join(f"{k}: {v}" for k, v in tags.items()), | |
| "はい" if phone.get("PersistentConnection") else "いいえ", | |
| AUDIO_ENHANCEMENT_MAP.get(voice_mode, "なし"), | |
| ] | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--instance-id", required=True, help="Connect instance ID") | |
| parser.add_argument( | |
| "--output", | |
| default=None, | |
| help="出力先CSVファイルパス(未指定時は connect_users_YYYYMMDD_HHMM.csv)", | |
| ) | |
| parser.add_argument("--limit", type=int, default=0, help="テスト用: 取得する最大ユーザー数(0=無制限)") | |
| parser.add_argument("--max-workers", type=int, default=5, help="describe_user並列実行数") | |
| parser.add_argument("--region", default=None, help="AWSリージョン(未指定時はデフォルト設定を使用)") | |
| parser.add_argument("--s3-bucket", default=None, help="出力CSVのアップロード先S3バケット名(未指定時はアップロードしない)") | |
| parser.add_argument("--s3-key", default=None, help="アップロード先S3キー(未指定時は--outputのファイル名を使用)") | |
| args = parser.parse_args() | |
| if args.output is None: | |
| args.output = f"connect_users_{datetime.now().strftime('%Y%m%d_%H%M')}.csv" | |
| client = make_client(region=args.region) | |
| rp_cache, sp_cache, hg_cache = NameCache(), NameCache(), NameCache() | |
| print("ユーザー一覧を取得中...", file=sys.stderr) | |
| user_ids = list_user_ids(client, args.instance_id, args.limit) | |
| total = len(user_ids) | |
| print(f"{total}件のユーザーを処理します", file=sys.stderr) | |
| rows_by_index = [None] * total | |
| done = 0 | |
| with ThreadPoolExecutor(max_workers=args.max_workers) as executor: | |
| futures = { | |
| executor.submit( | |
| build_row, client, args.instance_id, user_id, rp_cache, sp_cache, hg_cache | |
| ): index | |
| for index, user_id in enumerate(user_ids) | |
| } | |
| errors = [] | |
| for future in as_completed(futures): | |
| index = futures[future] | |
| try: | |
| rows_by_index[index] = future.result() | |
| except Exception as e: | |
| errors.append((user_ids[index], e)) | |
| rows_by_index[index] = [f"ERROR: {user_ids[index]}: {e}"] + [""] * (len(CSV_HEADER) - 1) | |
| done += 1 | |
| if done % 50 == 0 or done == total: | |
| print(f"{done}/{total} 件完了", file=sys.stderr) | |
| for user_id, e in errors: | |
| print(f"エラー: user_id={user_id}: {e}", file=sys.stderr) | |
| with open(args.output, "w", newline="", encoding="utf-8-sig") as f: | |
| writer = csv.writer(f, quoting=csv.QUOTE_ALL) | |
| writer.writerow(CSV_HEADER) | |
| writer.writerows(rows_by_index) | |
| print(f"出力完了: {args.output}", file=sys.stderr) | |
| if args.s3_bucket: | |
| s3_key = args.s3_key or os.path.basename(args.output) | |
| print(f"S3へアップロード中: s3://{args.s3_bucket}/{s3_key}", file=sys.stderr) | |
| upload_to_s3(args.output, args.s3_bucket, s3_key, region=args.region) | |
| print(f"アップロード完了: s3://{args.s3_bucket}/{s3_key}", file=sys.stderr) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment