我正在尝试通过 Python 脚本在 Google Cloud 上创建 IoT 设备。我已经设置了项目、IoT 注册表并验证了我的 GCloud,并将 GOOGLE_APPLICATION_CREDENTIALS 链接到相应服务帐户的 json。为什么我使用命令行创建帐户,例如 gcloud iot devices create dev01 --project=... --region=... --registry=...
,它有效。但是,我的 Python 脚本(通过命令提示符运行)似乎没有产生相同的结果。我使用https://cloud.google.com/iot/docs/samples/device-manager-samples#iot-core-create-rs256-python作为 iot_v1 参考。
# Generate Key
key = rsa.generate_private_key(backend=default_backend(), public_exponent=65537, key_size=2048)
# Get Public
public_key = key.public_key().public_bytes(serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH)
# Get Private
pem = key.private_bytes(encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption())
# Decode to UTF-8
private_key_str = pem.decode('utf-8')
public_key_str = public_key.decode('utf-8')
# Write keys
with open('Key Pairs/'+deviceName+'_private.pem', 'wb') as file:
file.write(pem)
with open('Key Pairs/' + deviceName + '_public.pem', 'wb') as file:
file.write(public_key)
# Create Device
client = iot_v1.DeviceManagerClient()
parent = client.registry_path(PROJECTID, REGION, REGISTRY)
deviceTemplate = {
'id': deviceName,
"credentials": [
{
"public_key": {
"format": iot_v1.PublicKeyFormat.RSA_X509_PEM,
"key": public_key_str,
}
}
]
}
client.create_device(request={'parent': parent, 'device': deviceTemplate})
慕的地8271018
相关分类