快速入门:使用适用于 IoT 中心设备预配服务的 Python 设备 SDK 创建和预配模拟的 X.509 设备Quickstart: Create and provision a simulated X.509 device using Python device SDK for IoT Hub Device Provisioning Service

在本快速入门中,要将开发计算机设置为 Python X.509 设备。In this quickstart, you provision a development machine as a Python X.509 device. 使用 Azure IoT Python SDK 中的示例设备代码将设备连接到 IoT 中心。You use sample device code from the Azure IoT Python SDK to connect the device to your IoT hub. 本示例结合使用了设备预配服务 (DPS) 和单个注册过程。An individual enrollment is used with the Device Provisioning Service (DPS) in this example.

先决条件Prerequisites

备注

初始的设备孪生状态配置仅在 IoT 中心的标准层中提供。The initial device twin state configuration is available only in the standard tier of IoT Hub. 有关基本和标准 IoT 中心层的详细信息,请参阅如何选择合适的 IoT 中心层For more information about the basic and standard IoT Hub tiers, see How to choose the right IoT Hub tier.

准备环境Prepare the environment

  1. 确保在计算机上安装 git 并将其添加到可供命令窗口访问的环境变量。Make sure git is installed on your machine and is added to the environment variables accessible to the command window. 请参阅软件自由保护组织提供的 Git 客户端工具,了解要安装的最新版 git 工具,其中包括 Git Bash,这是一个命令行应用,可以用来与本地 Git 存储库交互。See Software Freedom Conservancy's Git client tools for the latest version of git tools to install, which includes the Git Bash, the command-line app that you can use to interact with your local Git repository.

  2. 打开 Git Bash 提示符。Open a Git Bash prompt. 克隆 Azure IoT Python SDK 的 GitHub 存储库。Clone the GitHub repo for Azure IoT Python SDK.

    git clone https://github.com/Azure/azure-iot-sdk-python.git --recursive
    

创建自签名的 X.509 设备证书Create a self-signed X.509 device certificate

在本部分中,将创建自签名的 X.509 证书。In this section, you will create a self-signed X.509 certificate. 请务必记住以下几点:It is important to keep in mind the following points:

  • 自签名证书仅用于测试,不应在生产环境中使用。Self-signed certificates are for testing only, and should not be used in production.
  • 自签名证书的默认过期日期为一年。The default expiration date for a self-signed certificate is one year.

如果还没有用于对设备进行身份验证的设备证书,可以使用 OpenSSL 创建一个自签名证书,以便完成本文内容。If you don't already have your device certificates to authenticate a device, you can create a self-signed certificate with OpenSSL for testing with this article. Git 安装内容中附带了 OpenSSL。OpenSSL is included with the Git installation.

  1. 在 Git Bash 提示符下运行以下命令。Run the following command in the Git Bash prompt.

    winpty openssl req -outform PEM -x509 -sha256 -newkey rsa:4096 -keyout ./python-device.key.pem -out ./python-device.pem -days 365 -extensions usr_cert -subj "//CN=Python-device-01"
    

    重要

    仅当需要在 Windows 平台上使用 Git 来转义字符串时,才需要为使用者名称 (//CN=Python-device-01) 提供额外的西文斜杠。The extra forward slash given for the subject name (//CN=Python-device-01) is only required to escape the string with Git on Windows platforms.

  2. 当系统要求“输入 PEM 通行短语:”时,请使用通行短语 1234 进行测试。When asked to Enter PEM pass phrase:, use the pass phrase 1234 for testing with this article.

  3. 如果系统再次要求“验证 - 输入 PEM 通行短语:”,请再次使用通行短语 1234When asked again Verifying - Enter PEM pass phrase:, use the pass phrase 1234 again.

将在运行 openssl 命令的目录中生成测试证书文件 (python-device.pem) 和私钥文件 (python-device.key.pem)。A test certificate file (python-device.pem) and private key file (python-device.key.pem) are generated in the directory where you ran the openssl command.

在 DPS 中创建单个注册条目Create an individual enrollment entry in DPS

Azure IoT 设备预配服务支持两类注册:The Azure IoT Device Provisioning Service supports two types of enrollments:

本文演示要使用 IoT 中心预配的单个设备的单个注册过程。This article demonstrates an individual enrollment for a single device to be provisioned with an IoT hub.

  1. 登录到 Azure 门户,选择左侧菜单上的“所有资源”按钮,打开预配服务。Sign in to the Azure portal, select the All resources button on the left-hand menu and open your provisioning service.

  2. 在“设备预配服务”菜单中,选择“管理注册”。From the Device Provisioning Service menu, select Manage enrollments. 选择“个人注册”选项卡,然后选择顶部的“添加个人注册”按钮 。Select Individual Enrollments tab and select the Add individual enrollment button at the top.

  3. 在“添加注册”面板中,输入以下信息:In the Add Enrollment panel, enter the following information:

    • 选择“X.509”作为标识证明机制。Select X.509 as the identity attestation Mechanism.

    • 如果使用之前创建的测试证书,则在“主要证书 .pem 或 .cer 文件”下,选择“选择文件”,并选择证书文件“python-device.pem” 。Under the Primary certificate .pem or .cer file, choose Select a file to select the certificate file python-device.pem if you are using the test certificate created earlier.

    • (可选)可以提供以下信息:Optionally, you may provide the following information:

      • 选择与预配服务链接的 IoT 中心。Select an IoT hub linked with your provisioning service.
      • 使用设备所需的初始配置更新“初始设备孪生状态” 。Update the Initial device twin state with the desired initial configuration for the device.
    • 完成后,按“保存”按钮。Once complete, press the Save button.

      在门户中为 X.509 证明添加单个注册Add individual enrollment for X.509 attestation in the portal

    成功注册以后,X.509 设备会在“单个注册”选项卡的“注册 ID”列下显示为“Python-device-01” 。此注册值取自设备证书上的使用者名称。Upon successful enrollment, your X.509 device appears as Python-device-01 under the Registration ID column in the Individual Enrollments tab. This registration value comes from the subject name on the device certificate.

模拟设备Simulate the device

Python 设置示例 provision_x509.py 可在 azure-iot-sdk-python/azure-iot-device/samples/async-hub-scenarios 目录中找到。The Python provisioning sample, provision_x509.py is located in the azure-iot-sdk-python/azure-iot-device/samples/async-hub-scenarios directory. 此示例使用六个环境变量,通过 DPS 对 IoT 设备进行身份验证和预配。This sample uses six environment variables to authenticate and provision an IoT device using DPS. 这些环境变量包括:These environment variables are:

变量名称Variable name 说明Description
PROVISIONING_HOST 此值是用于连接 DPS 资源的全局终结点This value is the global endpoint used for connecting to your DPS resource
PROVISIONING_IDSCOPE 此值是 DPS 资源的 ID 范围This value is the ID Scope for your DPS resource
DPS_X509_REGISTRATION_ID 此值为设备的 ID。This value is the ID for your device. 它还必须与设备证书上的使用者名称相符It must also match the subject name on the device certificate
X509_CERT_FILE 设备证书文件名Your device certificate filename
X509_KEY_FILE 设备证书的私钥文件名The private key filename for your device certificate
PASS_PHRASE 用于对证书和私钥文件进行加密的密码 (1234)。The pass phrase you used to encrypt the certificate and private key file (1234).
  1. 在“设备预配服务”菜单中,选择“概述”。From the Device Provisioning Service menu, select Overview. 记下“ID 范围”和“全局设备终结点” 。Note your ID Scope and Global device endpoint.

    服务信息

  2. 在 Git Bash 提示符下,使用以下命令为全局设备终结点和 ID 范围添加环境变量。In your Git Bash prompt, use the following commands add the environment variables for the global device endpoint and ID Scope.

    $export PROVISIONING_HOST=global.azure-devices-provisioning.cn
    $export PROVISIONING_IDSCOPE=<ID scope for your DPS resource>
    
  3. IoT 设备的注册 ID 必须与设备证书上的使用者名称相符。The registration ID for the IoT device must match subject name on its device certificate. 如果生成了自签名测试证书,则 Python-device-01 是设备的使用者名称和注册 ID。If you generated a self-signed test certificate, Python-device-01 is the subject name and registration ID for the device.

    如果已有设备证书,可以使用 certutil 来验证用于设备的使用者公用名,如以下自签名测试证书示例所示:If you already have a device certificate, you can use certutil to verify the subject common name used for your device as shown below for a self-signed test certificate:

    $ certutil python-device.pem
    X509 Certificate:
    Version: 3
    Serial Number: fa33152fe1140dc8
    Signature Algorithm:
        Algorithm ObjectId: 1.2.840.113549.1.1.11 sha256RSA
        Algorithm Parameters:
        05 00
    Issuer:
        CN=Python-device-01
      Name Hash(sha1): 1dd88de40e9501fb64892b698afe12d027011000
      Name Hash(md5): a62c784820daa931b9d3977739b30d12
    
     NotBefore: 1/29/2021 7:05 PM
     NotAfter: 1/29/2022 7:05 PM
    
    Subject:
        ===> CN=Python-device-01 <===
      Name Hash(sha1): 1dd88de40e9501fb64892b698afe12d027011000
      Name Hash(md5): a62c784820daa931b9d3977739b30d12
    

    在 Git Bash 提示符下,按如下所示设置注册 ID 的环境变量:In the Git Bash prompt, set the environment variable for the registration ID as follows:

    $export DPS_X509_REGISTRATION_ID=Python-device-01
    
  4. 在 Git Bash 提示符下,为证书文件、私钥文件和通行短语设置环境变量。In the Git Bash prompt, set the environment variables for the certificate file, private key file, and pass phrase.

    $export X509_CERT_FILE=./python-device.pem
    $export X509_KEY_FILE=./python-device.key.pem
    $export PASS_PHRASE=1234
    
  5. 查看 provision_x509.py 的代码,如果未使用 Python 版本 3.7 或更高版本,请执行此处所述的代码更改以替换 asyncio.run(main()) 并保存更改。Review the code for provision_x509.py If your not using Python version 3.7 or later, make the code change mentioned here to replace asyncio.run(main()) and save your change.

  6. 运行该示例。Run the sample. 该示例将设备连接并预配到中心,并向中心发送一些测试消息。The sample will connect, provision the device to a hub, and send some test messages to the hub.

    $ winpty python azure-iot-sdk-python/azure-iot-device/samples/async-hub-scenarios/provision_x509.py
    RegistrationStage(RequestAndResponseOperation): Op will transition into polling after interval 2.  Setting timer.
    The complete registration result is
    Python-device-01
    TestHub12345.azure-devices.net
    initialAssignment
    null
    Will send telemetry from the provisioned device
    sending message #4
    sending message #7
    sending message #2
    sending message #8
    sending message #5
    sending message #9
    sending message #1
    sending message #6
    sending message #10
    sending message #3
    done sending message #4
    done sending message #7
    done sending message #2
    done sending message #8
    done sending message #5
    done sending message #9
    done sending message #1
    done sending message #6
    done sending message #10
    done sending message #3
    
  7. 在门户中,导航到链接到预配服务的 IoT 中心,并打开左侧菜单中“资源管理器”部分下的“IoT 设备”边栏选项卡。In the portal, navigate to the IoT hub linked to your provisioning service and open the IoT devices blade located under the Explorers section in the left menu. 将模拟的 X.509 设备成功预配到中心以后,设备 ID 会显示在“Device Explorer”边栏选项卡上,“状态”为“已启用”。On successful provisioning of the simulated X.509 device to the hub, its device ID appears on the Device Explorer blade, with STATUS as enabled. 如果在运行示例设备应用程序之前已打开边栏选项卡,则可能需要按顶部的“刷新”按钮。You might need to press the Refresh button at the top if you already opened the blade prior to running the sample device application.

    设备注册到 IoT 中心

备注

如果从设备的注册项中的默认值更改了“初始设备孪生状态”,则它会从中心拉取所需的孪生状态,并执行相应的操作。If you changed the initial device twin state from the default value in the enrollment entry for your device, it can pull the desired twin state from the hub and act accordingly. 有关详细信息,请参阅了解并在 IoT 中心内使用设备孪生For more information, see Understand and use device twins in IoT Hub.

清理资源Clean up resources

如果打算继续使用和探索设备客户端示例,请勿清理在本快速入门中创建的资源。If you plan to continue working on and exploring the device client sample, do not clean up the resources created in this quickstart. 如果不打算继续学习,请按以下步骤删除本快速入门中创建的所有资源。If you do not plan to continue, use the following steps to delete all resources created by this quickstart.

  1. 关闭计算机上的设备客户端示例输出窗口。Close the device client sample output window on your machine.
  2. 在 Azure 门户的左侧菜单中选择“所有资源”,然后选择设备预配服务。From the left-hand menu in the Azure portal, select All resources and then select your Device Provisioning service. 打开服务的“管理注册”边栏选项卡,然后选择“单个注册”选项卡 。选中在本快速入门中注册的设备的“注册 ID”旁边的复选框,然后按窗格顶部的“删除”按钮。Open the Manage Enrollments blade for your service, and then select the Individual Enrollments tab. Select the check box next to the REGISTRATION ID of the device you enrolled in this quickstart, and press the Delete button at the top of the pane.
  3. 在 Azure 门户的左侧菜单中选择“所有资源”,然后选择 IoT 中心 。From the left-hand menu in the Azure portal, select All resources and then select your IoT hub. 打开中心的“IoT 设备”边栏选项卡,选中在本快速入门中注册的设备的“设备 ID”旁边的复选框,然后按窗格顶部的“删除”按钮。Open the IoT devices blade for your hub, select the check box next to the DEVICE ID of the device you registered in this quickstart, and then press the Delete button at the top of the pane.

后续步骤Next steps

本快速入门介绍了如何在部署计算机上创建模拟 X.509 设备,以及如何使用门户中的 Azure IoT 中心设备预配服务将其预配到 IoT 中心。In this quickstart, you’ve created a simulated X.509 device on your development machine and provisioned it to your IoT hub using the Azure IoT Hub Device Provisioning Service on the portal. 若要了解如何以编程方式注册 X.509 设备,请继续阅读快速入门中关于 X.509 设备的编程注册内容。To learn how to enroll your X.509 device programmatically, continue to the quickstart for programmatic enrollment of X.509 devices.