最适合您的情况的身份验证流程是两条腿的 oauth。使用 oauth 2.0,您需要设置Service Account Credentials。
要使用服务帐户凭据构建管理服务:
import httplib2
import sys
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
def main(argv):
# Load the key in PKCS 12 format that you downloaded from the Google API
# Console when you created your Service account.
f = file('key.p12', 'rb')
key = f.read()
f.close()
# Create an httplib2.Http object to handle the HTTP requests and authorize it
# with the Credentials. Note that the first parameter, service_account_name,
# is the Email address created for the Service account. It must be the email
# address associated with the key that was created.
credentials = SignedJwtAssertionCredentials(
'XXXXX@developer.gserviceaccount.com',
key,
scope='https://www.googleapis.com/auth/admin.directory.user')
http = httplib2.Http()
http = credentials.authorize(http)
service = build('admin', 'directory_v1', http=http)
# Then you can use the service