Google 共有ドライブの一覧を特権管理者ロールで取得してみた

Google 共有ドライブは、作成された共有ドライブにメンバー登録されている人しか、その共有ドライブの存在がわかりません。そこで、特権管理者ロールを使用して全ての共有ドライブ一覧を取得してみます。

あるユーザーの共有ドライブ一覧

特権管理者ロールで表示される共有ドライブ一覧

コードで使用するサービスアカウントを「ドメイン全体の委任」に登録

コードの実行環境を準備

python3 -m venv .venv

. .venv/bin/activate

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

実行コード

from google.oauth2 import service_account
from googleapiclient.discovery import build

SCOPES = [
    'https://www.googleapis.com/auth/drive',
    'https://www.googleapis.com/auth/admin.directory.group.readonly',
    'https://www.googleapis.com/auth/admin.directory.user.readonly',
    'https://www.googleapis.com/auth/admin.directory.domain.readonly']
SERVICE_ACCOUNT_FILE = 'shared-drives.json'
ADMIN_USER = '[email protected]'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
creds = credentials.with_subject(ADMIN_USER)

service = build('drive', 'v3', credentials=creds)
results = service.drives().list(useDomainAdminAccess=True).execute()
items = results.get('drives', [])
for item in items:
    print(u'{0} ({1})'.format(item['name'], item['id']))

実行結果

$ python shared-drives.py
infosys2001 (0AM************9PVA)
hr2001 (0AO************9PVA)
all2023 (0AP************9PVA)

参考

https://support.google.com/a/answer/162106?hl=ja#start&setup&view

https://developers.google.com/drive/api/guides/manage-shareddrives?hl=ja

タグ: