You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python程序化获取Azure IoT设备连接字符串?

程序化获取Azure IoT Hub设备连接字符串的Python实现

下面给你两种可行的实现方式,替代手动粘贴和手动执行Azure CLI命令:

方法一:用Azure IoT Hub管理SDK(推荐)

这是官方推荐的程序化管理方式,稳定性和扩展性更好,适合批量处理设备。

1. 先安装依赖包

pip install azure-mgmt-iothub azure-identity

2. 代码实现

from azure.mgmt.iothub import IotHubClient
from azure.identity import DefaultAzureCredential
from azure.iot.device.aio import IoTHubDeviceClient
import asyncio

# 替换成你的实际参数
SUBSCRIPTION_ID = "ABCD1234"
HUB_NAME = "MY_HUB"
DEVICE_ID = "MY_DEVICE"

# 初始化认证和客户端
credential = DefaultAzureCredential()
iot_hub_client = IotHubClient(credential, SUBSCRIPTION_ID)

# 获取设备的主连接字符串
device_details = iot_hub_client.device_identity.get(HUB_NAME, DEVICE_ID)
conn_str = device_details.authentication.symmetric_key.primary_connection_string

# 连接设备的逻辑
async def connect_device():
    device_conn = IoTHubDeviceClient.create_from_connection_string(conn_str)
    await device_conn.connect()
    # 这里添加你的设备业务代码

if __name__ == "__main__":
    asyncio.run(connect_device())

说明:DefaultAzureCredential会自动适配多种认证场景——本地开发时用你az login的登录状态,Azure云环境中用托管身份,不用硬编码密钥,安全又方便。

方法二:直接调用Azure CLI命令(快速临时方案)

如果不想折腾SDK,也可以用Python调用本地的Azure CLI命令,解析输出结果:

import subprocess
import json
from azure.iot.device.aio import IoTHubDeviceClient
import asyncio

# 替换参数
SUBSCRIPTION_ID = "ABCD1234"
HUB_NAME = "MY_HUB"
DEVICE_ID = "MY_DEVICE"

# 构造CLI命令并执行
cmd = [
    "az", "iot", "hub", "device-identity", "connection-string", "show",
    "--device-id", DEVICE_ID,
    "--hub-name", HUB_NAME,
    "--subscription", SUBSCRIPTION_ID,
    "--output", "json"
]

result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
    output_data = json.loads(result.stdout)
    conn_str = output_data["connectionString"]
    
    # 连接设备
    async def connect_device():
        device_conn = IoTHubDeviceClient.create_from_connection_string(conn_str)
        await device_conn.connect()
    
    asyncio.run(connect_device())
else:
    print(f"获取失败: {result.stderr}")

注意:这种方法要求本地已经安装Azure CLI,并且通过az login完成了登录,适合临时脚本,批量处理的话还是推荐SDK。

内容的提问来源于stack exchange,提问作者Omar.Ebrahim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 17:31:13