Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
教程:在边缘网关上获取资产模型列表
你可以使用可用的子集Amazon IoT SiteWiseAPI 以及特定于边缘的 API,用于与资产模型及其边缘资产进行交互。本教程将引导您获取网关的临时凭证以及获取网关上的资产模型列表。
先决条件
在本教程的步骤中,您可以使用各种工具。要使用这些工具,请确保安装了相应的必备组件。
要完成本教程,您需要:
步骤 1:获取网关服务签名证书
要与网关上可用的 API 建立 TLS 连接,您需要一个可信证书。您可以使用 OpenSSL 生成此证书,或者Amazon OpsHub
- OpenSSL
-
打开终端并运行以下命令从中获取签名证书Amazon IoT SiteWise边缘网关。替换<sitewise_gateway_ip>
使用网关的 IP。
openssl s_client -connect <sitewise_gateway_ip>
:443 </dev/null 2>/dev/null | openssl x509 -outform PEM > GatewayCert.pem
- Amazon OpsHub
-
你可以用Amazon OpsHub为了Amazon IoT SiteWise。有关更多信息,请参阅管理网关:
本教程使用下载的网关证书的绝对路径。运行以下命令导出证书的完整路径,替换<absolute_path_to_certificate>
带有证书的路径:
export PATH_TO_CERTIFICATE='<absolute_path_to_certificate>
'
步骤 2:获取您的网关主机名
要完成本教程,您需要网关的主机名。要获取网关的主机名,请运行以下命令,替换<sitewise_gateway_ip>
使用网关的 IP:
openssl s_client -connect <sitewise_gateway_ip>
:443 </dev/null 2>/dev/null | grep -Po 'CN = \K.*'| head -1
运行以下命令导出主机名供以后使用,替换<your_edge_gateway_hostname>
使用您的网关的主机名:
export GATEWAY_HOSTNAME='<your_edge_gateway_hostname>
'
步骤 3:获取网关的临时证书
现在您已经有了网关的签名证书和主机名,您需要获取临时证书,以便可以在网关上运行 API。你可以通过以下方式获取这些证书Amazon OpsHub或者使用 API 直接从网关获取。
凭证每 4 小时过期一次,因此您应该在网关上使用 API 之前获取证书。请勿将凭证缓存超过 4 小时。
使用获取临时证书Amazon OpsHub
要使用Amazon OpsHub为了Amazon IoT SiteWise要获取您的临时凭证的应用程序,请执行以下操作:
登录应用程序。
选择 Settings。
对于身份验证,选择复制凭证。
扩展适合您环境的选项,然后选择复制。
保存凭证以备日后使用。
使用网关 API 获取临时证书
要使用网关 API 获取临时证书,你可以使用 Python 脚本或 curl,首先你需要有网关的用户名和密码。网关使用 SigV4 身份验证和授权。有关添加用户的更多信息,请参阅LDAP要么Linux 用户池。这些证书将在以下步骤中用于在您的网关上获取使用所需的本地证书Amazon IoT SiteWiseAPI。
- Python
-
使用 Python 获取证书
-
创建一个名为的文件get_credentials.py然后将以下代码复制到其中。
'''
The following demonstrates how to get the credentials from the 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 the AWS IoT SiteWise Edge 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("invalid 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:])
跑get_credentials.py从终端更换<gateway_username>
和<gateway_password>
使用您创建的凭证。
python3 get_credentials.py -e https://$GATEWAY_HOSTNAME -c $PATH_TO_CERTIFICATE -u '<gateway_username>
' -p '<gateway_password>
' -m 'linux'
- curl
-
使用 curl 获取凭证
使用<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"
}
从您的终端运行以下命令。
export AWS_ACCESS_KEY_ID=<accessKeyId>
export AWS_SECRET_ACCESS_KEY=<secretAccessKey>
export AWS_SESSION_TOKEN=<sessionToken>
export AWS_REGION=edge
第 4 步:在网关上获取资产模型列表
现在您已经有了签名证书、网关主机名和网关的临时证书,可以使用ListAssetModels
用于获取网关上资产模型列表的 API。
- Python
-
使用 Python 获取资产模型列表
-
创建一个名为的文件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)
跑list_asset_model.py从航站楼。
python3 list_asset_model.py
- 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
}