Register users with Google Admin SDK (python)

Introduction

I was managing users using GSuite (GoogleApps) and had to input a large amount of data. I often saw articles such as reading data in the tutorial, but there were not many articles about registration, so I will write an article if it helps.

What you need to do before writing code

Project registration

Create a project with an appropriate name from the Developer Console. プロジェクトの登録.png

Go back to the dashboard, select the project you created and add the API. APIを有効にする.png

Please enable "Admin SDK" and create an authentication key. --Create credentials with OAuth --Application type: Enter the name appropriately in "Other" AdminSDK1.png

An authentication key will be created and displayed in the list. Download it and save it in a suitable location. (In the code example: Save it as "client_secret_test.jso.json" under [your home directory] /.test_secrets/)

Almost ready to work.

Actual code

create.rb


# -*- coding: utf-8 -*-

import os
import httplib2
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

def main():
	try:
		import argparse
		parser = argparse.ArgumentParser(parents=[tools.argparser])
		flags = parser.parse_args()
	except ImportError:
		flags = None

	#Directory for storing authentication information "."Credentials" setting. Create if directory does not exist
	credential_dir = os.path.join(os.path.expanduser('~'), '.test_credentials')
	if not os.path.exists(credential_dir):
		os.makedirs(credential_dir)

	#Set and read the path of the authentication file
	credential_path = os.path.join(credential_dir, 'admin-directory_v1_test.json')
	store = Storage(credential_path)
	credentials = store.get()

	#Create if there is no authentication file
	if not credentials or credentials.invalid:

		#Set the range of functions to use
		scopes = [
			'https://www.googleapis.com/auth/admin.directory.user',
		]

		#Authentication key setting
		secret_dir = os.path.join(os.path.expanduser('~'), '.test_secrets')
		if not os.path.exists(secret_dir):
			os.makedirs(secret_dir)

		#Create an instance of the class that performs authentication processing from the authentication key
		flow = client.flow_from_clientsecrets(
			os.path.join(secret_dir, 'client_secret_test.json'), scopes)

		#Application name
		flow.user_agent = 'User register Test Tool'

		if flags:
				credentials = tools.run_flow(flow, store, flags)
		else: # Python 2.6 Compatibility processing
			credentials = tools.run(flow, store)
		print('I saved the certificate:' + credential_path)

	#Authenticate
	http = credentials.authorize(httplib2.Http())
	app_admin_service = discovery.build('admin', 'directory_v1', http=http)

	#Create user information to create
	register_data = {
		'primaryEmail':'[email protected]',
		'name':{
			'givenName':'Taro',
			'familyName':'Yamada',
		},
		'suspended':False, #Do not put account suspended
		'password':'p-a-s-s-w-o-r-d',
	}

	#Registration execution
	results = app_admin_service.users().insert(body=register_data).execute()

	if(int(results['id']) > 0):
		print("Create a google account!")
	else:
		print("Failed to create google account")


if __name__ == '__main__':
	main()

When you run the program, the browser will launch and you will be asked for permission. Click OK to run it. 許可リスエスト.png

reference

G Suite Admin SDK Directory API

Recommended Posts

Register users with Google Admin SDK (python)
Study Python with Google Colaboratory
Access Google Drive with Python
Try using Python with Google Cloud Functions
Working with OpenStack using the Python SDK
[GCP] Operate Google Cloud Storage with Python
Touch virtual robots with Pepper's Python SDK
[Continued] Try PLC register access with Python
Upload images to Google Drive with Python
FizzBuzz with Python3
Csv output from Google search with [Python]! 【Easy】
Scraping with Python
Play with Google Spread Sheets in python (OAuth)
Scraping with Python
Python with Go
Try running Google Chrome with Python and Selenium
Twilio with Python
Integrate with Python
Play with 2016-Python
AES256 with python
Tested with Python
python starts with ()
with syntax (Python)
Bingo with python
Zundokokiyoshi with python
Upload files to Google Drive with Lambda (Python)
[Python] Troubleshooting before accessing Google Spreadsheet with gspread
Excel with Python
Microcomputer with Python
Cast with python
Various memorandums when using sdk of LINE Messaging API with Python (2.7.9) + Google App Engine
[GCP] [Python] Deploy API serverless with Google Cloud Functions!
Fleet provisioning with AWS IoT SDK for Python v2
Easy way to scrape with python using Google Colab
Register a ticket with redmine API using python requests
Getting Started with Google App Engine for Python & PHP
Serial communication with Python
Authenticate Google with Django
Zip, unzip with python
Django 1.11 started with Python3.6
Python with eclipse + PyDev.
Socket communication with Python
Data analysis with python 2
Scraping with Python (preparation)
Try scraping with Python.
Learning Python with ChemTHEATER 03
Sequential search with Python
"Object-oriented" learning with python
Handling yaml with python
Solve AtCoder 167 with python
Serial communication with python
[Python] Use JSON with Python
Learning Python with ChemTHEATER 05-1
Learn Python with ChemTHEATER
Run prepDE.py with python3
1.1 Getting Started with Python
Collecting tweets with Python
Binarization with OpenCV / Python
3. 3. AI programming with Python
Kernel Method with Python
Scraping with Python + PhantomJS