View a markdown version of this page

教程:在上列出资产模型AWS IoT SiteWise边缘网关 - AWS IoT SiteWise

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

教程:在上列出资产模型AWS IoT SiteWise边缘网关

您可以使用可用AWS IoT SiteWise的 API 的子集以及特定于边缘的 API 来与资源模型及其边缘资产进行交互。本教程将引导您获取 AWS IoT SiteWise Edge 网关的临时凭证以及获取 SiteWise Edge 网关上的资产模型列表。

先决条件

在本教程的步骤中,您可以使用各种工具。要使用这些工具,请确保您安装了相应的必备工具。

要完成本教程,您需要:

步骤 1:获取 SiteWise Edge 网关服务签名证书

要与 SiteWise Edge 网关上可用的 API 建立 TLS 连接,您需要一个可信证书。您可以使用 OpenSSL 或AWS OpsHub为生成此证书。AWS IoT SiteWise

OpenSSL
注意

您需要安装 OpenSSL 才能运行此命令。

打开终端并运行以下命令从 SiteWise Edge 网关获取签名证书。<sitewise_gateway_ip>替换为 SiteWise 边缘网关的 IP。

openssl s_client -connect <sitewise_gateway_ip>:443 </dev/null 2>/dev/null | openssl x509 -outform PEM > GatewayCert.pem
AWS OpsHubforAWS IoT SiteWise

你可以用AWS OpsHub于AWS IoT SiteWise。有关更多信息,请参阅 管理 SiteWise Edge 网关。

本教程使用下载的 SiteWise Edge 网关证书的绝对路径。运行以下命令导出证书的完整路径,将 <absolute_path_to_certificate> 替换为证书的路径:

export PATH_TO_CERTIFICATE='<absolute_path_to_certificate>'

步骤 2:获取您的 SiteWise Edge 网关主机名

注意

您需要安装 OpenSSL 才能运行此命令。

要完成本教程,您需要提供 SiteWise Edge 网关的主机名。要获取 SiteWise Edge 网关的主机名,请运行以下命令,<sitewise_gateway_ip>替换为 SiteWise Edge 网关的 IP:

openssl s_client -connect <sitewise_gateway_ip>:443 </dev/null 2>/dev/null | grep -Po 'CN = \K.*'| head -1

运行以下命令导出主机名供以后使用,<your_edge_gateway_hostname>替换为 SiteWise Edge 网关的主机名:

export GATEWAY_HOSTNAME='<your_edge_gateway_hostname>'

步骤 3:获取 SiteWise Edge 网关的临时证书

现在,您已获得 SiteWise Edge 网关的签名证书和主机名,您需要获取临时证书,以便可以在网关上运行 API。您可以通过 Edge 网关获取这些凭证AWS OpsHub,AWS IoT SiteWise也可以使用 API 直接从 SiteWise Edge 网关获取这些证书。

重要

凭证每 4 小时过期一次,因此您应该在使用 SiteWise Edge 网关上的 API 之前获取证书。请勿将凭证缓存超过 4 小时。

使用获取临时证书AWS OpsHub适合AWS IoT SiteWise

要使用AWS IoT SiteWise应用程序AWS OpsHub获取您的临时证书,请执行以下操作:

  1. 登录应用程序。

  2. 选择设置。

  3. 对于身份验证,选择复制凭证。

  4. 展开适合您环境的选项,再选择复制。

  5. 保存凭证以供稍后使用。

使用 SiteWise Edge 网关 API 获取临时证书

要使用 SiteWise Edge 网关 API 获取临时证书,可以使用 Python 脚本或 curl,首先需要有 SiteWise Edge 网关的用户名和密码。边 SiteWise 缘网关使用 Sigv4 身份验证和授权。有关添加用户的更多信息,请参阅 LDAP 或 Linux 用户群体。在以下步骤中,将使用这些凭证在您的 SiteWise Edge 网关上获取使用 AWS IoT SiteWise API 所需的本地证书。

Python
注意

您需要安装 urllib3 和 Python3。

获取 Python 使用凭证
  1. 创建一个名为 get_credentials.py 的文件,再将以下代码复制到其中。

    ''' The following demonstrates how to get the credentials from the SiteWise Edge gateway. You will need to add local users or connect your system to LDAP/AD https://docs.aws.amazon.com/iot-sitewise/latest/userguide/manage-gateways-ggv2.html#create-user-pool Example usage: python3 get_credentials.py -e https://<gateway_hostname> -c <path_to_certificate> -u '<gateway_username>' -p '<gateway_password>' -m '<method>' ''' import urllib3 import json import urllib.parse import sys import os import getopt """ This function retrieves theAWS IoT SiteWiseEdge gateway credentials. """ def get_credentials(endpoint,certificatePath, user, password, method): http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs= certificatePath) encoded_body = json.dumps({ "username": user, "password": password, "authMechanism": method, }) url = urllib.parse.urljoin(endpoint, "/authenticate") response = http.request('POST', url, headers={'Content-Type': 'application/json'}, body=encoded_body) if response.status != 200: raise Exception(f'Failed to authenticate! Response status {response.status}') auth_data = json.loads(response.data.decode('utf-8')) accessKeyId = auth_data["accessKeyId"] secretAccessKey = auth_data["secretAccessKey"] sessionToken = auth_data["sessionToken"] region = "edge" return accessKeyId, secretAccessKey, sessionToken, region def print_help(): print('Usage:') print(f'{os.path.basename(__file__)} -e <endpoint> -c <path/to/certificate> -u <user> -p <password> -m <method> -a <alias>') print('') print('-e, --endpoint edge gateway endpoint. Usually the Edge gateway hostname.') print('-c, --cert_path path to downloaded gateway certificate') print('-u, --user Edge user') print('-p, --password Edge password') print('-m, --method (Optional) Authentication method (linux, winnt, ldap), default is linux') sys.exit() def parse_args(argv): endpoint = "" certificatePath = None user = None password = None method = "linux" try: opts, args = getopt.getopt(argv, "he:c:u:p:m:", ["endpoint=","cert_path=", "user=", "password=", "method="]) except getopt.GetoptError: print_help() for opt, arg in opts: if opt == '-h': print_help() elif opt in ("-e", "--endpoint"): endpoint = arg elif opt in ("-u", "--user"): user = arg elif opt in ("-p", "--password"): password = arg elif opt in ("-m", "--method"): method = arg.lower() elif opt in ("-c", "--cert_path"): certificatePath = arg if method not in ['ldap', 'linux', 'winnt']: print("not valid method parameter, required are ldap, linux, winnt") print_help() if (user == None or password == None): print("To authenticate against edge user, password have to be passed together, and the region has to be set to 'edge'") print_help() if(endpoint == ""): print("You must provide a valid and reachable gateway hostname") print_help() return endpoint,certificatePath, user, password, method def main(argv): # get the command line args endpoint, certificatePath, user, password, method = parse_args(argv) accessKeyId, secretAccessKey, sessionToken, region=get_credentials(endpoint, certificatePath, user, password, method) print("Copy and paste the following credentials into the shell, they are valid for 4 hours:") print(f"export AWS_ACCESS_KEY_ID={accessKeyId}") print(f"export AWS_SECRET_ACCESS_KEY={secretAccessKey}") print(f"export AWS_SESSION_TOKEN={sessionToken}") print(f"export AWS_REGION={region}") print() if __name__ == "__main__": main(sys.argv[1:])
  2. 使用您创建的凭证替换 <gateway_username> 和 <gateway_password> 并在终端运行 get_credentials.py。

    python3 get_credentials.py -e https://$GATEWAY_HOSTNAME -c $PATH_TO_CERTIFICATE -u '<gateway_username>' -p '<gateway_password>' -m 'linux'
curl
注意

您需要安装 curl。

获取 curl 使用凭证
  1. 使用您创建的凭证替换 <gateway_username> 和 <gateway_password> 并在终端运行命令。

    curl --cacert $PATH_TO_CERTIFICATE --location \ -X POST https://$GATEWAY_HOSTNAME:443/authenticate \ --header 'Content-Type: application/json' \ --data-raw '{ "username": "<gateway_username>", "password": "<gateway_password>", "authMechanism": "linux" }'

    该响应应当与以下内容相似:

    { "username": "sweuser", "accessKeyId": "<accessKeyId>", "secretAccessKey": "<secretAccessKey>", "sessionToken": "<sessionToken>", "sessionExpiryTime": "2022-11-17T04:51:40.927095Z", "authMechanism": "linux", "role": "edge-user" }
  2. 从您的终端运行以下命令。

    export AWS_ACCESS_KEY_ID=<accessKeyId> export AWS_SECRET_ACCESS_KEY=<secretAccessKey> export AWS_SESSION_TOKEN=<sessionToken> export AWS_REGION=edge

第 4 步:获取 SiteWise Edge 网关上的资产模型列表

现在,您已拥有签名证书、 SiteWise Edge 网关主机名和 SiteWise Edge 网关的临时证书,您可以使用 ListAssetModels API 获取 SiteWise Edge 网关上的资产模型列表。

Python
注意

你需要安装 Python3、Boto 3。BotoCore

使用 Python 获取资产模型列表
  1. 创建一个名为 list_asset_model.py 的文件,再将以下代码复制到其中。

    import json import boto3 import botocore import os # create the client using the credentials client = boto3.client("iotsitewise", endpoint_url= "https://"+ os.getenv("GATEWAY_HOSTNAME"), region_name=os.getenv("AWS_REGION"), aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"), aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"), aws_session_token=os.getenv("AWS_SESSION_TOKEN"), verify=os.getenv("PATH_TO_CERTIFICATE"), config=botocore.config.Config(inject_host_prefix=False)) # call the api using local credentials response = client.list_asset_models() print(response)
  2. 从终端运行 list_asset_model.py。

    python3 list_asset_model.py
curl
注意

您需要安装 curl。

使用 curl 获取资产模型列表

从终端运行以下命令。

curl \ --request GET https://$GATEWAY_HOSTNAME:443/asset-models \ --cacert $PATH_TO_CERTIFICATE \ --aws-sigv4 "aws:amz:edge:iotsitewise" \ --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \ -H "x-amz-security-token:$AWS_SESSION_TOKEN"

该响应应当与以下内容相似:

{ "assetModelSummaries": [ { "arn": "arn:aws:iotsitewise:{region}:{account-id}:asset-model/{asset-model-id}", "creationDate": 1.669245291E9, "description": "This is a small example asset model", "id": "{asset-model-id}", "lastUpdateDate": 1.669249038E9, "name": "Some Metrics Model", "status": { "error": null, "state": "ACTIVE" } }, . . . ], "nextToken": null }