loader image

[python]googleグループごとのメンバー情報取得

from future import print_function
from math import dist
from os import write
import os.path
import csv
from unicodedata import name
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
SCOPES = [‘https://www.googleapis.com/auth/admin.directory.group.readonly’]
def main():
creds = None
#token.jsonが実在すればTRUE
if os.path.exists(‘token.json’):
#Jsonから資格情報を作成
creds = Credentials.from_authorized_user_file(‘token.json’, SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
‘credentials.json’, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open(‘token.json’, ‘w’) as token:
token.write(creds.to_json())
try:
#create service
service = build(‘admin’, ‘directory_v1’, credentials=creds)
var = list()
#txtを読み込みlist型変数に入れていく
f = open(‘./target_group.txt’, ‘r’)
datalist = f.readlines()
for data in datalist:
#add groups(remove newline)
var.append(data.strip())
f.close()
#varに入れたgroup emailを読み込んでいく
i=0
while (i < len(var)):
labels = [‘kind’, ‘etag’, ‘id’,’email’,’role’,’type’,’status’,’group_email’]
result = service.members().list(groupKey=var[i]).execute()
result=result.get(‘members’)
#writing
with open(‘./result.csv’, ‘a’ ,newline=”) as f:
writer = csv.DictWriter(f, fieldnames=labels )
if i == 0:
writer.writeheader()

for elem in result:
elem[‘group_email’]=var[i]
writer.writerow(elem)
i=i+1
except HttpError as error:
# TODO(developer) – Handle errors from drive API.
print(f’An error occurred: {error}’)

if name == ‘main‘:
main()

コメント

タイトルとURLをコピーしました