面向使用服务账号的客户的 Python 快速入门
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
按照本快速入门指南中的步骤操作,大约 10 分钟后,您就可以拥有一个简单的 Python 命令行应用,该应用使用服务账号向零触摸注册客户 API 发出请求。
前提条件
如需运行本快速入门,您需要:
- 一个服务账号,该账号与您的“零触摸注册”客户账号相关联。请参阅获取
开始。
- Python 3.0 或更高版本。
- pip 软件包管理
工具。
- 能够连接到互联网并使用网络浏览器。
第 1 步:启用零触摸注册 API
- 使用此向导在 Google Developers Console 中创建或选择项目,并自动启用该 API。点击继续,然后点击转到凭据。
- 将您要访问哪些数据?设置为应用数据。
- 点击下一步。系统应该会提示您创建 Service
。
- 为服务账号名称指定一个描述性名称。
- 记下服务账号 ID(看起来像电子邮件地址),因为您稍后将用到它。
- 将角色设置为服务账号 >Service Account User。
- 点击完成以完成服务账号的创建过程。
- 点击您创建的服务账号的电子邮件地址。
- 点击**密钥**。
- 点击**添加密钥**,然后点击**创建新密钥**。
- 在“密钥类型”中,选择“JSON”。
- 点击创建,私钥便会下载到您的计算机。
- 点击“关闭”。
- 将该文件移至您的工作目录中,并将其重命名为
service_account_key.json
。
第 2 步:安装 Google 客户端库
运行以下命令以使用 pip 安装库:
pip install --upgrade google-api-python-client oauth2client
请参阅此库的安装
页面
选项。
第 3 步:设置示例
在您的工作目录中创建一个名为 quickstart.py
的文件。复制以下代码并保存文件。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Zero-touch enrollment quickstart sample.
This script forms the quickstart introduction to the zero-touch enrollemnt
customer API. To learn more, visit https://developer.google.com/zero-touch
"""
import sys
from apiclient import discovery
import httplib2
from oauth2client.service_account import ServiceAccountCredentials
# A single auth scope is used for the zero-touch enrollment customer API.
SCOPES = ['https://www.googleapis.com/auth/androidworkzerotouchemm']
SERVICE_ACCOUNT_KEY_FILE = 'service_account_key.json'
def get_credential():
"""Creates a Credential object with the correct OAuth2 authorization.
Uses the service account key stored in SERVICE_ACCOUNT_KEY_FILE.
Returns:
Credentials, the user's credential.
"""
credential = ServiceAccountCredentials.from_json_keyfile_name(
SERVICE_ACCOUNT_KEY_FILE, SCOPES)
if not credential or credential.invalid:
print('Unable to authenticate using service account key.')
sys.exit()
return credential
def get_service():
"""Creates a service endpoint for the zero-touch enrollment API.
Builds and returns an authorized API client service for v1 of the API. Use
the service endpoint to call the API methods.
Returns:
A service Resource object with methods for interacting with the service.
"""
http_auth = get_credential().authorize(httplib2.Http())
return discovery.build('androiddeviceprovisioning', 'v1', http=http_auth)
def main():
"""Runs the zero-touch enrollment quickstart app.
"""
# Create a zero-touch enrollment API service endpoint.
service = get_service()
# Get the customer's account. Because a customer might have more
# than one, limit the results to the first account found.
response = service.customers().list(pageSize=1).execute()
if 'customers' not in response:
# No accounts found for the user. Confirm the Google Account
# that authorizes the request can access the zero-touch portal.
print('No zero-touch enrollment account found.')
sys.exit()
customer_account = response['customers'][0]['name']
# Send an API request to list all the DPCs available using the customer
# account.
results = service.customers().dpcs().list(parent=customer_account).execute()
# Print out the details of each DPC.
for dpc in results['dpcs']:
# Some DPCs may not have a name, so replace with a marker.
if 'dpcName' in dpc:
dpcName = dpc['dpcName']
else:
dpcName = "-"
print('Name:{0} APK:{1}'.format(dpcName, dpc['packageName']))
if __name__ == '__main__':
main()
第 4 步:添加服务账号密钥
将您在创建服务账号时下载的 service_account_key.json
复制到您的工作目录。
第 5 步:运行示例
请借助操作系统的帮助运行文件中的脚本。在 UNIX 和 Mac 上
请在终端中运行以下命令:
python quickstart.py
备注
- 请勿与任何人分享您的
service_account_key.json
文件。请注意
请勿将其包含在源代码库中您可以参阅有关处理服务账号密钥的更多建议。
了解详情
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-29。
[null,null,["最后更新时间 (UTC):2025-08-29。"],[[["\u003cp\u003eThis quickstart guide helps you create a simple Python command-line app that interacts with the zero-touch enrollment customer API using a service account in about 10 minutes.\u003c/p\u003e\n"],["\u003cp\u003eYou will need a service account linked to your zero-touch enrollment customer account, Python 3.0 or greater, the pip package management tool, internet access, and a web browser to run this guide.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves enabling the zero-touch enrollment API, installing the Google client library, setting up the sample code, and adding your downloaded service account key file, along with running the sample file.\u003c/p\u003e\n"],["\u003cp\u003eThe sample code demonstrates how to authenticate using a service account key, create a service endpoint for the zero-touch enrollment API, retrieve customer account information, and list available device policy controllers (DPCs).\u003c/p\u003e\n"],["\u003cp\u003eIt is crucial to manage the \u003ccode\u003eservice_account_key.json\u003c/code\u003e file securely, avoiding sharing or including it in source code repositories, as it poses a security risk if mishandled.\u003c/p\u003e\n"]]],["First, enable the zero-touch enrollment API and create a service account, noting its ID. Assign the \"Service Account User\" role, generate a JSON key, download it, and rename it to `service_account_key.json`. Next, install the Google client library using `pip`. Create `quickstart.py`, copy the provided Python code, and save it. Place the renamed key file into your working directory. Finally, run the `quickstart.py` script via the command line.\n"],null,["# Python quickstart for customers using a service account\n\nFollow the steps in this quickstart guide, and in about 10 minutes you have\na simple Python command-line app that makes requests to the zero-touch\nenrollment customer API using a service account.\n\nPrerequisites\n-------------\n\nTo run this quickstart, you need:\n\n- A service account, that's linked to you zero-touch enrollment customer account. See [Get\n started](/zero-touch/guides/customer/service-accounts).\n- Python 3.0 or greater.\n- The [pip](https://pypi.python.org/pypi/pip) package management tool.\n- Access to the internet and a web browser.\n\nStep 1: Turn on the zero-touch enrollment API\n---------------------------------------------\n\n1. Use [this\n wizard](https://console.developers.google.com/start/api?id=androiddeviceprovisioning.googleapis.com) to create or select a project in the Google Developers Console and automatically turn on the API. Click **Continue** , then **Go to credentials**.\n2. Set **What data will you be accessing?** to *Application data*.\n3. Click **Next**. You should be prompted to create a service account.\n4. Give a descriptive name for **Service account name**.\n5. Note the **Service account ID** (it looks like an email address) because you'll use it later.\n6. Set **Role** to *Service Accounts \\\u003e Service Account User*.\n7. Click **Done** to finish creating the service account.\n8. Click the email address for the service account that you created.\n9. Click \\*\\*Keys\\*\\*.\n10. Click \\*\\*Add key\\*\\*, then click \\*\\*Create new key\\*\\*.\n11. For \\*\\*Key type\\*\\*, select \\*\\*JSON\\*\\*.\n12. Click **Create** and the private key downloads to your computer.\n13. Click \\*\\*Close\\*\\*.\n14. Move the file to your working directory and rename it `service_account_key.json`.\n\n| **Warning:** Service account keys can become a security risk if not managed carefully. For advice see [best practices for managing API keys](https://cloud.google.com/iam/docs/best-practices-for-managing-service-account-keys).\n\nStep 2: Install the Google client library\n-----------------------------------------\n\nRun the following command to install the library using pip: \n\n pip install --upgrade google-api-python-client oauth2client\n\nSee the library's [installation\npage](/api-client-library/python/start/installation) for different installation\noptions.\n\nStep 3: Set up the sample\n-------------------------\n\nCreate a file named `quickstart.py` in your working directory. Copy in the\nfollowing code and save the file. \n\n```python\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Zero-touch enrollment quickstart sample.\n\nThis script forms the quickstart introduction to the zero-touch enrollemnt\ncustomer API. To learn more, visit https://developer.google.com/zero-touch\n\"\"\"\n\nimport sys\nfrom apiclient import discovery\nimport httplib2\nfrom oauth2client.service_account import ServiceAccountCredentials\n\n# A single auth scope is used for the zero-touch enrollment customer API.\nSCOPES = ['https://www.googleapis.com/auth/androidworkzerotouchemm']\nSERVICE_ACCOUNT_KEY_FILE = 'service_account_key.json'\n\n\ndef get_credential():\n \"\"\"Creates a Credential object with the correct OAuth2 authorization.\n\n Uses the service account key stored in SERVICE_ACCOUNT_KEY_FILE.\n\n Returns:\n Credentials, the user's credential.\n \"\"\"\n credential = ServiceAccountCredentials.from_json_keyfile_name(\n SERVICE_ACCOUNT_KEY_FILE, SCOPES)\n\n if not credential or credential.invalid:\n print('Unable to authenticate using service account key.')\n sys.exit()\n return credential\n\n\ndef get_service():\n \"\"\"Creates a service endpoint for the zero-touch enrollment API.\n\n Builds and returns an authorized API client service for v1 of the API. Use\n the service endpoint to call the API methods.\n\n Returns:\n A service Resource object with methods for interacting with the service.\n \"\"\"\n http_auth = get_credential().authorize(httplib2.Http())\n return discovery.build('androiddeviceprovisioning', 'v1', http=http_auth)\n\n\ndef main():\n \"\"\"Runs the zero-touch enrollment quickstart app.\n \"\"\"\n # Create a zero-touch enrollment API service endpoint.\n service = get_service()\n\n # Get the customer's account. Because a customer might have more\n # than one, limit the results to the first account found.\n response = service.customers().list(pageSize=1).execute()\n\n if 'customers' not in response:\n # No accounts found for the user. Confirm the Google Account\n # that authorizes the request can access the zero-touch portal.\n print('No zero-touch enrollment account found.')\n sys.exit()\n customer_account = response['customers'][0]['name']\n\n # Send an API request to list all the DPCs available using the customer\n # account.\n results = service.customers().dpcs().list(parent=customer_account).execute()\n\n # Print out the details of each DPC.\n for dpc in results['dpcs']:\n # Some DPCs may not have a name, so replace with a marker.\n if 'dpcName' in dpc:\n dpcName = dpc['dpcName']\n else:\n dpcName = \"-\"\n print('Name:{0} APK:{1}'.format(dpcName, dpc['packageName']))\n\n\nif __name__ == '__main__':\n main()\n```\n\nStep 4: Add your service account key\n------------------------------------\n\nCopy the `service_account_key.json` you downloaded when you created your\nservice account into your working directory.\n\nStep 5: Run the sample\n----------------------\n\nUse your operating system's help to run the script in the file. On UNIX and Mac\ncomputers, run the command below in your terminal: \n\n python quickstart.py\n\nNotes\n-----\n\n- Avoid sharing your `service_account_key.json` file with anyone. Be careful not to include it in source code repositories. You can read more advice on [handling service account secrets](https://cloud.google.com/iam/docs/best-practices-for-managing-service-account-keys).\n\nLearn more\n----------\n\n- [Google Developers Console help documentation](/console/help/new)\n- [Google APIs Client for Python documentation](/api-client-library/python)\n- [pip User Guide](https://pip.pypa.io/en/stable/user_guide/)"]]