无论我选择哪个 eventName,我都会收到类似
Invalid request: Event UPDATE_USER not found in manifest.
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES).with_subject(DELEGATED_ADMIN_EMAIL)
service = build('admin', 'reports_v1', credentials=credentials)
request = service.activities().list(
userKey='all',
applicationName='admin',
eventName=event_name,
startTime=start_time,
endTime=end_time
)
while request is not None:
response = request.execute()
logs.extend(response.get('items', []))
request = service.activities().list_next(request, response)
事件名称已更改为CHANGE_NAME、CHANGE_EMAIL、UPDATE_USER。我无法弄清楚我需要哪个 eventName 来提取已发生的更改列表。
Google 域名位于 Google Workspace Enterprise 的最高层之一。所以我确信这不是因为他们的等级太低。
粒度。
虽然此方法提供了大量数据,但它并非旨在捕获您所需的详细级别的特定更改,例如用户电子邮件或名称修改。因此,为了更准确地跟踪用户电子邮件和姓名更改,您可以尝试使用
Google Workspace Directory API (GWD),而不是采用这种方法。通过此API可以直接访问用户信息,包括电子邮件、姓名和其他属性。
因此您可以尝试按照以下步骤操作:
import time
from googleapiclient.discovery import build
from google.oauth2.service_account import Credentials
from google.auth.exceptions import RefreshError
from googleapiclient.errors import HttpError
import sqlite3
from datetime import datetime
# Configuration
SERVICE_ACCOUNT_FILE = 'path/to/your/service_account.json'
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']
DOMAIN = 'your_domain.com'
SUBJECT = 'admin@your_domain.com' # Admin email for domain-wide delegation
DB_FILE = 'user_data.db'
def get_service():
creds = Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_creds = creds.with_subject(SUBJECT)
return build('admin', 'directory_v1', credentials=delegated_creds)
def initialize_db():
conn = sqlite3.connect(DB_FILE)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS users
(email TEXT PRIMARY KEY, full_name TEXT, last_updated TEXT)''')
conn.commit()
return conn
def get_users(service, page_token=None):
try:
results = service.users().list(domain=DOMAIN, pageToken=page_token,
projection='full').execute()
return results.get('users', []), results.get('nextPageToken')
except HttpError as error:
print(f'An error occurred: {error}')
return [], None
def update_user_data(conn, email, full_name):
c = conn.cursor()
current_time = datetime.now().isoformat()
c.execute('''INSERT OR REPLACE INTO users (email, full_name, last_updated)
VALUES (?, ?, ?)''', (email, full_name, current_time))
conn.commit()
def check_for_changes(conn, email, full_name):
c = conn.cursor()
c.execute('SELECT full_name FROM users WHERE email = ?', (email,))
result = c.fetchone()
if result is None:
print(f'New user added: {email} - {full_name}')
return True
elif result[0] != full_name:
print(f'Name changed for {email}: {result[0]} -> {full_name}')
return True
return False
def main():
service = get_service()
conn = initialize_db()
page_token = None
while True:
users, page_token = get_users(service, page_token)
for user in users:
email = user['primaryEmail']
full_name = user['name']['fullName']
if check_for_changes(conn, email, full_name):
update_user_data(conn, email, full_name)
if not page_token:
break
conn.close()
if __name__ == '__main__':
while True:
try:
main()
print("Sleeping for 1 hour...")
time.sleep(3600) # Run every hour
except RefreshError:
print("Token refresh error. Check your credentials.")
break
except Exception as e:
print(f"An unexpected error occurred: {e}")
time.sleep(300) # Wait 5 minutes before retrying
您可以根据您的具体需求更新等待时间。
代码的总体概述是:
首先,我使用GWD API直接