

# ML Detect 指南
<a name="dd-detect-ml-getting-started"></a>

**注意**  
ML Detect 在以下区域中不可用：  
亚太地区（马来西亚）

在本入门指南中，您将创建一个 ML Detect 安全配置文件，该配置文件使用机器学习 (ML) 根据设备中的历史指标数据创建预期行为模型。当 ML Detect 正在创建 ML 模型时，您可以监控其进度。构建 ML 模型后，您可以持续查看和调查告警，并缓解已发现的问题。

有关 ML Detect 及其 API 和 CLI 命令的更多信息，请参阅 [ML Detect](dd-detect-ml.md)。

**Topics**
+ [

## 先决条件
](#ml-detect-prereqs)
+ [

## 如何在控制台中使用 ML Detect
](#dd-detect-ml-console)
+ [

## 如何将 （ML Detect 与 CLI 一起使用
](#dd-detect-ml-cli)

## 先决条件
<a name="ml-detect-prereqs"></a>
+ AWS 账户。如果您尚未拥有账户，请参阅[设置](https://docs.aws.amazon.com/iot/latest/developerguide/dd-setting-up.html)。

## 如何在控制台中使用 ML Detect
<a name="dd-detect-ml-console"></a>

**Topics**
+ [

### 启用 ML Detect
](#enable-ml-detect-console)
+ [

### 监控您的 ML 模型状态
](#monitor-ml-models-console)
+ [

### 查看您的 ML Detect 告警
](#review-ml-alarms-console)
+ [

### 微调您的机器学习（ML）告警
](#fine-tune-ml-models-console)
+ [

### 标记告警的验证状态
](#mark-your-alarms)
+ [

### 缓解已确定的设备问题
](#mitigate-ml-issues-console)

### 启用 ML Detect
<a name="enable-ml-detect-console"></a>

以下流程详细介绍了如何在控制台中设置 ML Detect。

1. 首先，确保您的设备将按 [ML Detect 最低要求](dd-detect-ml.md#dd-detect-ml-requirements)中的定义要求创建最小的数据点，以进行持续训练和刷新模型。要进行数据收集，请确保您的安全配置文件已附加到目标，该目标可以是事物或事物组。

1. 在 [AWS IoT 控制台](https://console.aws.amazon.com/iot)的导航窗格中，展开 **Defend**（防护）。选择 **Detect**（检测）、**Security profiles**（安全配置文件）、**Create security profile**（创建安全配置文件），然后选择 **Create ML anomaly Detect profile**（创建 ML 异常检测配置文件）。

1. 在 **Set basic configurations**（设置基本配置）页面上，执行以下操作。
   + 在 **Target**（目标）项下，选择您的目标设备组。
   + 在 **Security profile name**（安全配置文件名称）中，输入您的安全配置文件的名称。
   + （可选）在 **Description**（说明）项下，您可以编写 ML 配置文件的简述。
   + 在 **Selected metric behaviors in Security Profile**（安全配置文件中特定的指标行为）项下，选择要监控的指标。  
![\[“创建 ML 安全配置文件”配置页面，已将“所有已注册的事物”选择为目标，列出了诸如授权失败和连接尝试次数之类的指标行为，并具有用于添加云端或设备端指标的选项。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-set-basic.png)

   完成此操作后，选择**下一步**。

1. 在 **Set SNS (optional)**（设置 SNS（可选））页面上，为设备违反配置文件中的行为时的告警通知指定 SNS 主题。选择要用于发布到选定 SNS 主题的 IAM 角色。

   如果您还没有 SNS 角色，请使用以下步骤创建具有所需的适当权限和信任关系的角色。
   + 导航到 [IAM 控制台](https://console.aws.amazon.com/iam/)。在导航窗格中，选择**角色**，然后选择**创建角色**。
   + 在**Select type of trusted entity**（选择信任实体的类型）项下，选择 **AWS service**（亚马逊云科技服务）。然后，在 **Choose a use case**（选择使用案例）中，选择 **IoT**，在 **Select your use case**（选择您的使用案例）项下，选择 **IoT - Device Defender Mitigation Actions**（IoT - Device Defender 缓解操作）。完成操作后，选择 **Next: Permissions**（下一步：权限）。
   + 在 **Attached permissions policies**（附加权限策略）项下，确保选择了 **AWSIoTDeviceDefenderPublishFindingsToSNSMitigationAction**，然后选择 **Next: Tags**（下一步：标签）。  
![\[AWS IoT Device Defender 角色的权限策略表，其中包含策略名称、有关每个策略提供访问权限的内容的描述，以及用于筛选或搜索策略的选项。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-sns-findings.png)
   + 在 **Add tags (optional)**（添加标签（可选））项下，您可以添加要与角色关联的任何标签。完成此操作后，选择 **Next: Review (下一步：审核)**。
   + 在 **Review**（审核）项下，请为您的角色指定一个名称，并确保 **AWSIoTDeviceDefenderPublishFindingsToSNSMitigationAction** 列示在 **Permissions**（权限）项下，且 **AWS service: iot.amazonaws.com** 列在 **Trust relationships**（信任关系）项下。完成后，选择 **Create role**（创建角色）。  
![\[IAM 角色摘要页面显示 Sample-SNS-role 详细信息，例如角色 ARN、描述、实例配置文件 ARN、路径、创建时间、最长会话持续时间以及所应用的“AWS IoT Device Defender 将调查发现发布到 SNS 缓解操作”策略\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-detect-permissions.png)  
![\[IAM Sample-SNS-role 摘要显示角色 ARN、角色描述（向 AWS IoT Device Defender 提供发布 SNS 通知的写入权限）、路径、创建时间和可信实体\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-detect-trust-relationships.png)

1. 在 **Edit Metric behavior**（编辑指标行为）页面上，您可以自定义您的机器学习（ML）行为设置。  
![\[“编辑指标行为”部分，包含授权失败、输入字节数和连接尝试次数指标，可用于为警报触发器配置数据点以及配置通知和 ML Detect 置信度。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-update-config.png)

1. 完成此操作后，选择**下一步**。

1. 在 **Review configuration**（查看配置）页面上，验证您希望机器学习监控的行为，然后选择 **Next**（下一步）。  
![\[编辑 ML 安全配置文件页面显示 Smart_lights_ML_Detect_Security_Profile，目标为“所有已注册的事物”，并具有对应于授权失败、输出字节数、连接尝试次数和断开连接次数的指标行为。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-review-config.png)

   

1. 创建了安全配置文件之后，您将会被重定向到 **Security Profiles**（安全配置文件）页面，此处将显示新创建的安全配置文件。
**注意**  
初始 ML 模型训练和创建需要 14 天才能完成。如果您的设备上存在任何异常活动，则在完成后您应会看到告警。

### 监控您的 ML 模型状态
<a name="monitor-ml-models-console"></a>

当您的 ML 模型处于初始训练阶段时，您可以通过执行以下步骤随时监控其进度。

1. 在 [AWS IoT 控制台](https://console.aws.amazon.com/iot)中的导航窗格中，展开 **Defend**（防护），然后选择 **Detect**（检测）、**Security profiles**（安全配置文件）。

1. 在 **Security Profiles**（安全配置文件）页面上，选择您要查看的安全配置文件。然后，选择 **Behaviors and ML training**（行为和机器学习（ML）训练）。

1. 在 **Behaviors and ML training**（行为和机器学习（ML）训练）页面上，检查 ML 模型的训练进度。

   在模型状态为 **Active**（激活）后，它将开始根据您的使用情况做出 Detect 决策，并每天更新配置文件。  
![\[控制面板显示了用于监控 TCP/UDP 侦听端口和已建立的 TCP 连接的低置信度机器学习模型。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-active-state.png)

**注意**  
如果您的模型未按预期进行，请确保您的设备满足 [最低要求](dd-detect-ml.md#dd-detect-ml-requirements) 的要求。

### 查看您的 ML Detect 告警
<a name="review-ml-alarms-console"></a>

在构建 ML 模型并准备进行数据推理之后，您可以定期查看和调查由模型识别的告警。

1. 在 [AWS IoT 控制台](https://console.aws.amazon.com/iot)的导航窗格中，展开 **Defend**（防护），然后选择 **Detect**（检测）、**Alarms**（告警）。  
![\[AWS IoT Device Defender 警报列表显示了 5 个主动授权失败警报，包括事物名称、安全配置文件、行为类型、行为名称、上次发出时间和验证状态等列。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-alarms.png)

1. 如果您导航到 **History**（历史记录）选项卡上，您还可以查看不再处于告警状态的设备相关详细信息。  
![\[折线图显示两周期间内处于警报中、已清除和已失效状态的警报，警报数量位于 y 轴上，日期位于 x 轴上。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-history-alarm.png)

   若要获取更多信息，请在 **Manage**（管理）项下选择 **Things**（事物），选择您想要查看更多详细信息的事物，然后导航到 **Defender metrics**（Defender 指标）。您可以访问 **Defender metrics graph**（Defender 指标图形）并对 **Active**（激活）选项卡中告警的任何内容进行调查。在这种情况下，图形显示了启动告警的消息大小峰值。您可以看到告警随后被清除。  
![\[IoT 事物控制面板显示了消息大小最大值指标图，指定日期和时间的峰值为 801 字节。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-defender-metrics.png)

### 微调您的机器学习（ML）告警
<a name="fine-tune-ml-models-console"></a>

在构建 ML 模型并准备好进行数据评估之后，您可以更新安全配置文件的机器学习（ML）行为设置以更改配置。以下流程介绍如何在 AWS CLI 中更新您的安全配置文件的机器学习（ML）行为设置。

1. 在 [AWS IoT 控制台](https://console.aws.amazon.com/iot)中的导航窗格中，展开 **Defend**（防护），然后选择 **Detect**（检测）、**Security profiles**（安全配置文件）。

1. 在 **Security Profiles**（安全配置文件）页面上，选中要查看的安全配置文件旁边的复选框。然后依次选择 **Actions**（操作）、**Edit**（编辑）。  
![\[AWS IoT Device Defender 安全配置文件列表显示了配置文件名称、ML 阈值类型、保留的行为、目标事物、创建日期、通知状态\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-fine-tune.png)

1. 在 **Set basic configurations**（设置基本配置）项下，您可以调整安全配置文件目标事物组或更改要监控的指标。  
![\[“创建 ML 安全配置文件”配置页面，已将“所有已注册的事物”选择为目标，列出了诸如授权失败和连接尝试次数之类的指标行为，并具有用于添加云端或设备端指标的选项\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-set-basic.png)

1. 您可以通过导航到 **Edit metric behaviors**（编辑指标行为）更新以下任意一项。
   + 启动告警所需的 ML 模型数据点
   + 清除告警所需的 ML 模型数据点
   + ML Detect 置信级别
   + ML Detect 通知，例如 **Not suppressed**（未隐藏）、**Suppressed**（隐藏）。  
![\[“编辑指标行为”部分，其中包含用于为 ML 安全配置文件配置授权失败、输出字节数和连接尝试次数指标的选项。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-update-config-2.png)

### 标记告警的验证状态
<a name="mark-your-alarms"></a>

通过设置验证状态并提供该验证状态的描述来标记告警。这会帮助您和您的团队识别不必回应的告警。

1. 在 [AWS IoT 控制台](https://console.aws.amazon.com/iot/)的导航窗格中，展开 **Defend**（防护），然后选择 **Detect**（检测）、**Alarms**（告警）。选择告警以标记其验证状态。  
![\[AWS IoT Device Defender 警报视图显示了 IoT 控制台事物的主动授权失败行为事件，例如 iotconsole-6f8379bc-c245-4ffe-8ef7-b2b52e78975c 以及 fdsa 安全配置文件。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-alarm-select.png)

1. 选择 **Mark verification state**（标记验证状态）。验证状态模式打开。

1. 选择适当的验证状态，输入验证说明（可选），然后选择 **Mark**（标记）。此操作将验证状态和描述分配给选定的告警。  
![\[用于标记警报验证状态的对话框，选项包括：未知、真警报、误报、良性真警报。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-alarm-state-window.png)

### 缓解已确定的设备问题
<a name="mitigate-ml-issues-console"></a>

1. *（可选）*在设置隔离缓解措施之前，让我们设置一个隔离组，我们会将违规的设备移动到该组。您也可以使用现有组。

1. 导航到 **Manage**（管理）、**Thing groups**（事物组），然后选择 **Create Thing Group**（创建事物组）。为您的事物组命名。在本教程中，我们将事物组命名为 `Quarantine_group`。在 **Thing Group**（事物组）、**Security**（安全）中，将以下策略应用于事物组。

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Deny",
               "Action": "iot:*",
               "Resource": "*"
           }
       ]
   }
   ```

------  
![\[AWS IoT 控制台“创建事物组”页面，具有“创建事物组”按钮。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-create-thing-group.png)

   完成后，选择 **Create thing group**（创建事务组）。

1. 现在我们已经创建了事物组，让我们创建一个缓解操作，将告警中的设备移动到 `Quarantine_group`。

   在 **Defend**（防护）、**Mitigation actions**（缓解操作）中，选择 **Create**（创建）。  
![\[AWS IoT Device Defender 缓解操作配置表单，包含操作名称、操作类型、权限、操作执行角色和事物组等字段。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-miti-create.png)

1. 在 **Create new mitigation action**（创建新的缓解操作）页面上，输入以下信息。
   + **Action name**（操作名称）：指定缓解操作的名称，例如 **Quarantine\$1action**。
   + **Action type**（操作类型）：选择操作的类型。我们将选择 **Add things to things group (Audit or Detect mitigation)**（将事物添加到事物组（审计或 Detect 缓解））。
   + **Action execution role**（操作执行角色）：创建角色或选择现有角色（如果您之前创建了角色）。
   + **Parameters**（参数）：选择事物组。我们可以使用之前创建的 `Quarantine_group`。  
![\[AWS IoT Device Defender 缓解操作配置表单，包含操作名称、操作类型、权限、操作执行角色和事物组等字段。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-miti-create-form.png)

   完成此操作后，选择**保存**。现在，您可以执行缓解操作，将告警中的设备移动到隔离事物组，并在调查期间执行缓解操作来隔离设备。

1. 导航到 **Defender**、**Detect**（检测）、**Alarms**（告警），您可以查看 **Active**（激活）状态下有哪些设备处于告警状态。  
![\[AWS IoT Device Defender 警报列表显示了 5 个主动授权失败警报，包括事物名称、安全配置文件、行为类型、行为名称、上次发出时间和验证状态等列。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-alarms.png)

   选择要移动到隔离组的设备，然后选择 **Start Mitigation Actions**（启动缓解操作）。

1. 在 **Start mitigation actions**（启动缓解操作）、**Start Actions**（启动操作）项下，选择您之前创建的缓解操作。例如，我们将选择 **Quarantine\$1action**，然后选择 **Start**（启动）。此时将打开操作任务页面。  
![\[缓解操作对话框，其中“udml7”列为受影响的事物，具有用于确认不可逆操作的复选框以及用于选择要执行的操作的下拉列表。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-start-action.png)

1. 设备现在被隔离在 **Quarantine\$1group** 中，您可以调查引发告警的问题的根本原因。完成调查后，您可以将设备移出事物组或采取进一步操作。  
![\[AWS IoT Device Defender Detect 操作任务表显示了一项隔离操作，用于向 quarantine_group 事物组添加事物。\]](http://docs.aws.amazon.com/zh_cn/iot-device-defender/latest/devguide/images/dd-ml-action-tasks.png)

   

## 如何将 （ML Detect 与 CLI 一起使用
<a name="dd-detect-ml-cli"></a>

下面的介绍了如何使用 CLI 设置 ML Detect。

**Topics**
+ [

### 启用 ML Detect
](#enable-ml-detect-cli)
+ [

### 监控您的 ML 模型状态
](#monitor-ml-models-cli)
+ [

### 查看您的 ML Detect 告警
](#review-ml-alarms-cli)
+ [

### 微调您的机器学习（ML）告警
](#fine-tune-ml-models-cli)
+ [

### 标记告警的验证状态
](#mark-verification-state-cli)
+ [

### 缓解已确定的设备问题
](#mitigate-issues-cli)

### 启用 ML Detect
<a name="enable-ml-detect-cli"></a>

以下流程介绍如何在 AWS CLI 中启用 ML Detect。

1. 确保您的设备将如 [ML Detect 最低要求](dd-detect-ml.md#dd-detect-ml-requirements)中定义创建所需的最小数据点，以进行持续训练和模型更新。为了进行数据收集，请确保您的事物位于附加到安全配置文件的事物组中。

1. 使用 `[create-security-profile](https://docs.aws.amazon.com/cli/latest/reference/iot/create-security-profile.html)` 命令创建 ML Detect 安全配置文件。以下示例创建一个名为 *security-profile-for-smart-lights* 的安全配置文件，用于检查发送的消息数量、授权失败次数、连接尝试次数以及断开连接次数。此示例使用 `mlDetectionConfig` 以确定该指标将使用 ML Detect 模型。

   ```
   aws iot create-security-profile \
       --security-profile-name security-profile-for-smart-lights \
       --behaviors \
        '[{
       "name": "num-messages-sent-ml-behavior",
       "metric": "aws:num-messages-sent",
       "criteria": {
         "consecutiveDatapointsToAlarm": 1,
         "consecutiveDatapointsToClear": 1,
         "mlDetectionConfig": {
           "confidenceLevel": "HIGH"
         }
       },
       "suppressAlerts": true
     },
     {
       "name": "num-authorization-failures-ml-behavior",
       "metric": "aws:num-authorization-failures",
       "criteria": {
         "consecutiveDatapointsToAlarm": 1,
         "consecutiveDatapointsToClear": 1,
         "mlDetectionConfig": {
           "confidenceLevel": "HIGH"
         }
       },
       "suppressAlerts": true
     },
     {
       "name": "num-connection-attempts-ml-behavior",
       "metric": "aws:num-connection-attempts",
       "criteria": {
         "consecutiveDatapointsToAlarm": 1,
         "consecutiveDatapointsToClear": 1,
         "mlDetectionConfig": {
           "confidenceLevel": "HIGH"
         }
       },
       "suppressAlerts": true
     },
     {
       "name": "num-disconnects-ml-behavior",
       "metric": "aws:num-disconnects",
       "criteria": {
         "consecutiveDatapointsToAlarm": 1,
         "consecutiveDatapointsToClear": 1,
         "mlDetectionConfig": {
           "confidenceLevel": "HIGH"
         }
       },
       "suppressAlerts": true
     }]'
   ```

   输出：

   ```
   {
       "securityProfileName": "security-profile-for-smart-lights",
       "securityProfileArn": "arn:aws:iot:eu-west-1:123456789012:securityprofile/security-profile-for-smart-lights"
     }
   ```

1. 接下来，将您的安全配置文件与一个或多个事物组关联。使用 `[attach-security-profile](https://docs.aws.amazon.com/cli/latest/reference/iot/attach-security-profile.html)` 命令将事物组附加到您的安全配置文件。下面的示例将名为 *ML\$1Detect\$1beta\$1static\$1group* 的事务组关联到了 *security-profile-for-smart-lights* 安全配置文件。

   ```
   aws iot attach-security-profile \
   --security-profile-name security-profile-for-smart-lights \
   --security-profile-target-arn arn:aws:iot:eu-west-1:123456789012:thinggroup/ML_Detect_beta_static_group
   ```

   输出：

   无。

1. 创建完整的安全配置文件后，ML 模型将开始训练。初始 ML 模型训练和构建需要 14 天才能完成。14 天后，如果您的设备上有异常活动，则可能会看到告警。

### 监控您的 ML 模型状态
<a name="monitor-ml-models-cli"></a>

以下流程介绍如何监控正在进行训练的 ML 模型。
+ 使用 `[get-behavior-model-training-summaries](https://docs.aws.amazon.com/cli/latest/reference/iot/get-behavior-model-training-summaries.html)` 命令查看 ML 模型的进度。以下示例获取 *security-profile-for-smart-lights* 安全配置文件的 ML 模型训练进度摘要。`modelStatus` 会显示模型是否已完成训练，或是仍在等待针对特定行为的构建。

  ```
  aws iot get-behavior-model-training-summaries \
     --security-profile-name security-profile-for-smart-lights
  ```

  输出：

  ```
  {
      "summaries": [
          {
              "securityProfileName": "security-profile-for-smart-lights",
              "behaviorName": "Messages_sent_ML_behavior",
              "trainingDataCollectionStartDate": "2020-11-30T14:00:00-08:00",
              "modelStatus": "ACTIVE",
              "datapointsCollectionPercentage": 29.408,
              "lastModelRefreshDate": "2020-12-07T14:35:19.237000-08:00"
          },
          {
              "securityProfileName": "security-profile-for-smart-lights",
              "behaviorName": "Messages_received_ML_behavior",
              "modelStatus": "PENDING_BUILD",
              "datapointsCollectionPercentage": 0.0
          },
          {
              "securityProfileName": "security-profile-for-smart-lights",
              "behaviorName": "Authorization_failures_ML_behavior",
              "trainingDataCollectionStartDate": "2020-11-30T14:00:00-08:00",
              "modelStatus": "ACTIVE",
              "datapointsCollectionPercentage": 35.464,
              "lastModelRefreshDate": "2020-12-07T14:29:44.396000-08:00"
          },
          {
              "securityProfileName": "security-profile-for-smart-lights",
              "behaviorName": "Message_size_ML_behavior",
              "trainingDataCollectionStartDate": "2020-11-30T14:00:00-08:00",
              "modelStatus": "ACTIVE",
              "datapointsCollectionPercentage": 29.332,
              "lastModelRefreshDate": "2020-12-07T14:30:44.113000-08:00"
          },
          {
              "securityProfileName": "security-profile-for-smart-lights",
              "behaviorName": "Connection_attempts_ML_behavior",
              "trainingDataCollectionStartDate": "2020-11-30T14:00:00-08:00",
              "modelStatus": "ACTIVE",
              "datapointsCollectionPercentage": 32.891999999999996,
              "lastModelRefreshDate": "2020-12-07T14:29:43.121000-08:00"
          },
          {
              "securityProfileName": "security-profile-for-smart-lights",
              "behaviorName": "Disconnects_ML_behavior",
              "trainingDataCollectionStartDate": "2020-11-30T14:00:00-08:00",
              "modelStatus": "ACTIVE",
              "datapointsCollectionPercentage": 35.46,
              "lastModelRefreshDate": "2020-12-07T14:29:55.556000-08:00"
          }
      ]
  }
  ```

**注意**  
如果您的模型未按预期进行，请确保您的设备满足 [最低要求](dd-detect-ml.md#dd-detect-ml-requirements) 的要求。

### 查看您的 ML Detect 告警
<a name="review-ml-alarms-cli"></a>

在构建 ML 模型并准备好进行数据评估之后，您可以定期查看由模型推断的任何告警。以下流程介绍如何在 AWS CLI 中查看您的告警。
+ 要查看所有活动告警，请使用 `[list-active-violations](https://docs.aws.amazon.com/cli/latest/reference/iot/list-active-violations.html)` 命令。

  ```
  aws iot list-active-violations \
  --max-results 2
  ```

  输出：

  ```
  {
      "activeViolations": []
  }
  ```

  或者，您可以使用 `[list-violation-events](https://docs.aws.amazon.com/cli/latest/reference/iot/list-violation-events.html)` 命令查看在给定时间内发现的所有违规行为。以下示例列出了从 2020 年 9 月 22 日 5:42:13 GMT 到 2020 年 10 月 26 日 5:42:13 GMT 之间的违规事件。

  ```
  aws iot list-violation-events \
      --start-time 1599500533 \ 
      --end-time 1600796533 \
      --max-results 2
  ```

  输出：

  ```
  {
      "violationEvents": [
          {
              "violationId": "1448be98c09c3d4ab7cb9b6f3ece65d6",
              "thingName": "lightbulb-1",
              "securityProfileName": "security-profile-for-smart-lights",
              "behavior": {
                  "name": "LowConfidence_MladBehavior_MessagesSent",
                  "metric": "aws:num-messages-sent",
                  "criteria": {
                      "consecutiveDatapointsToAlarm": 1,
                      "consecutiveDatapointsToClear": 1,
                      "mlDetectionConfig": {
                          "confidenceLevel": "HIGH"
                      }
                  },
                  "suppressAlerts": true
              },
              "violationEventType": "alarm-invalidated",
              "violationEventTime": 1600780245.29
          },
          {
              "violationId": "df4537569ef23efb1c029a433ae84b52",
              "thingName": "lightbulb-2",
              "securityProfileName": "security-profile-for-smart-lights",
              "behavior": {
                  "name": "LowConfidence_MladBehavior_MessagesSent",
                  "metric": "aws:num-messages-sent",
                  "criteria": {
                      "consecutiveDatapointsToAlarm": 1,
                      "consecutiveDatapointsToClear": 1,
                      "mlDetectionConfig": {
                          "confidenceLevel": "HIGH"
                      }
                  },
                  "suppressAlerts": true
              },
              "violationEventType": "alarm-invalidated",
              "violationEventTime": 1600780245.281
          }
      ],
      "nextToken": "Amo6XIUrsOohsojuIG6TuwSR3X9iUvH2OCksBZg6bed2j21VSnD1uP1pflxKX1+a3cvBRSosIB0xFv40kM6RYBknZ/vxabMe/ZW31Ps/WiZHlr9Wg7R7eEGli59IJ/U0iBQ1McP/ht0E2XA2TTIvYeMmKQQPsRj/eoV9j7P/wveu7skNGepU/mvpV0O2Ap7hnV5U+Prx/9+iJA/341va+pQww7jpUeHmJN9Hw4MqW0ysw0Ry3w38hOQWEpz2xwFWAxAARxeIxCxt5c37RK/lRZBlhYqoB+w2PZ74730h8pICGY4gktJxkwHyyRabpSM/G/f5DFrD9O5v8idkTZzBxW2jrbzSUIdafPtsZHL/yAMKr3HAKtaABz2nTsOBNre7X2d/jIjjarhon0Dh9l+8I9Y5Ey+DIFBcqFTvhibKAafQt3gs6CUiqHdWiCenfJyb8whmDE2qxvdxGElGmRb+k6kuN5jrZxxw95gzfYDgRHv11iEn8h1qZLD0czkIFBpMppHj9cetHPvM+qffXGAzKi8tL6eQuCdMLXmVE3jbqcJcjk9ItnaYJi5zKDz9FVbrz9qZZPtZJFHp"
  }
  ```

### 微调您的机器学习（ML）告警
<a name="fine-tune-ml-models-cli"></a>

构建 ML 模型并准备好进行数据评估后，您可以更新安全配置文件的 ML 行为设置以更改配置。以下流程介绍如何在 AWS CLI 中更新您的安全配置文件的机器学习（ML）行为设置。
+ 要更改安全配置文件的 ML 行为设置，请使用 `[update-security-profile](https://docs.aws.amazon.com/cli/latest/reference/iot/update-security-profile.html)` 命令。以下示例通过更改部分行为的 `confidenceLevel` 并取消隐藏所有行为的通知，从而更新了 *security-profile-for-smart-lights* 安全配置文件的行为。

  ```
  aws iot update-security-profile \
      --security-profile-name security-profile-for-smart-lights \
      --behaviors \
       '[{
        "name": "num-messages-sent-ml-behavior",
        "metric": "aws:num-messages-sent",
        "criteria": {
            "mlDetectionConfig": {
                "confidenceLevel" : "HIGH"
            }
        },
        "suppressAlerts": false
    },
    {
        "name": "num-authorization-failures-ml-behavior",
        "metric": "aws:num-authorization-failures",
        "criteria": {
            "mlDetectionConfig": {
                "confidenceLevel" : "HIGH"
            }
        },
        "suppressAlerts": false
    },
    {
        "name": "num-connection-attempts-ml-behavior",
        "metric": "aws:num-connection-attempts",
        "criteria": {
            "mlDetectionConfig": {
                "confidenceLevel" : "HIGH"
            }
        },
        "suppressAlerts": false
    },
    {
        "name": "num-disconnects-ml-behavior",
        "metric": "aws:num-disconnects",
        "criteria": {
            "mlDetectionConfig": {
                "confidenceLevel" : "LOW"
            }
        },
        "suppressAlerts": false
  
    }]'
  ```

  输出：

  ```
   {
      "securityProfileName": "security-profile-for-smart-lights",
      "securityProfileArn": "arn:aws:iot:eu-west-1:123456789012:securityprofile/security-profile-for-smart-lights",
      "behaviors": [
          {
              "name": "num-messages-sent-ml-behavior",
              "metric": "aws:num-messages-sent",
              "criteria": {
                  "mlDetectionConfig": {
                      "confidenceLevel": "HIGH"
                  }
              }
          },
          {
              "name": "num-authorization-failures-ml-behavior",
              "metric": "aws:num-authorization-failures",
              "criteria": {
                  "mlDetectionConfig": {
                      "confidenceLevel": "HIGH"
                  }
              }
          },
          {
              "name": "num-connection-attempts-ml-behavior",
              "metric": "aws:num-connection-attempts",
              "criteria": {
                  "mlDetectionConfig": {
                      "confidenceLevel": "HIGH"
                  }
              },
              "suppressAlerts": false
          },
          {
              "name": "num-disconnects-ml-behavior",
              "metric": "aws:num-disconnects",
              "criteria": {
                  "mlDetectionConfig": {
                      "confidenceLevel": "LOW"
                  }
              },
              "suppressAlerts": true
          }
      ],
      "version": 2,
      "creationDate": 1600799559.249,
      "lastModifiedDate": 1600800516.856
  }
  ```

### 标记告警的验证状态
<a name="mark-verification-state-cli"></a>

您可以使用验证状态标记告警，帮助对告警进行分类并调查异常情况。
+ 用验证状态和状态描述标记告警。例如，要将告警的验证状态设置为误报，请使用以下命令：

  ```
  aws iot put-verification-state-on-violation --violation-id 12345  --verification-state FALSE_POSITIVE --verification-state-description "This is dummy description"  --endpoint https://us-east-1.iot.amazonaws.com --region us-east-1
  ```

  输出：

  无。

### 缓解已确定的设备问题
<a name="mitigate-issues-cli"></a>

1. 使用 `[create-thing-group](https://docs.aws.amazon.com/cli/latest/reference/iot/create-thing-group.html)` 命令为缓解操作创建事物组。在下面的示例中，我们创建了一个名为 **ThingGroupForDetectMitigationAction** 的事物组。

   ```
   aws iot create-thing-group —thing-group-name ThingGroupForDetectMitigationAction
   ```

   输出：

   ```
   {
    "thingGroupName": "ThingGroupForDetectMitigationAction",
    "thingGroupArn": "arn:aws:iot:us-east-1:123456789012:thinggroup/ThingGroupForDetectMitigationAction",
    "thingGroupId": "4139cd61-10fa-4c40-b867-0fc6209dca4d"
   }
   ```

1. 接下来，使用 `[create-mitigation-action](https://docs.aws.amazon.com/cli/latest/reference/iot/create-mitigation-action.html)` 命令创建缓解操作。在以下示例中，我们使用了 IAM 角色的 ARN 创建了一个名为 **detect\$1mitigation\$1action** 的缓解操作，该 IAM 角色专用于应用缓解操作。我们还将定义操作类型和该操作的参数。在这种情况下，我们的缓解措施会将事物移动到我们之前创建的名为 **ThingGroupForDetectMitigationAction** 的事物组。

   ```
   aws iot create-mitigation-action --action-name detect_mitigation_action \
   --role-arn arn:aws:iam::123456789012:role/MitigationActionValidRole \
   --action-params \  
   '{
        "addThingsToThingGroupParams": {
            "thingGroupNames": ["ThingGroupForDetectMitigationAction"],
            "overrideDynamicGroups": false
        }
    }'
   ```

   输出：

   ```
   {
    "actionArn": "arn:aws:iot:us-east-1:123456789012:mitigationaction/detect_mitigation_action",
    "actionId": "5939e3a0-bf4c-44bb-a547-1ab59ffe67c3"
   }
   ```

1. 使用 `[start-detect-mitigation-actions-task](https://docs.aws.amazon.com/cli/latest/reference/iot/start-detect-mitigation-actions-task.html)` 命令启动缓解操作任务。`task-id`、`target` 和 `actions` 是必要的参数。

   ```
   aws iot start-detect-mitigation-actions-task \
       --task-id taskIdForMitigationAction \
       --target '{ "violationIds" : [ "violationId-1", "violationId-2" ] }' \
       --actions "detect_mitigation_action" \
       --include-only-active-violations \
       --include-suppressed-alerts
   ```

   输出：

   ```
   {
       "taskId": "taskIdForMitigationAction"
   }
   ```

1. （可选）要查看任务中包含的缓解操作执行，请使用 `[list-detect-mitigation-actions-executions](https://docs.aws.amazon.com/cli/latest/reference/iot/list-detect-mitigation-actions-executions.html)` 命令。

   ```
   aws iot list-detect-mitigation-actions-executions \
       --task-id taskIdForMitigationAction \
       --max-items 5 \
       --page-size 4
   ```

   输出：

   ```
   {
       "actionsExecutions": [
           {
               "taskId": "e56ee95e - f4e7 - 459 c - b60a - 2701784290 af",
               "violationId": "214_fe0d92d21ee8112a6cf1724049d80",
               "actionName": "underTest_MAThingGroup71232127",
               "thingName": "cancelDetectMitigationActionsTaskd143821b",
               "executionStartDate": "Thu Jan 07 18: 35: 21 UTC 2021",
               "executionEndDate": "Thu Jan 07 18: 35: 21 UTC 2021",
               "status": "SUCCESSFUL",
           }
       ]
   }
   ```

1. （可选）使用 `[describe-detect-mitigation-actions-task](https://docs.aws.amazon.com/cli/latest/reference/iot/describe-detect-mitigation-actions-task.html)` 命令获取有关缓解操作任务的信息。

   ```
   aws iot describe-detect-mitigation-actions-task \
       --task-id taskIdForMitigationAction
   ```

   输出：

   ```
   {
       "taskSummary": {
           "taskId": "taskIdForMitigationAction",
           "taskStatus": "SUCCESSFUL",
           "taskStartTime": 1609988361.224,
           "taskEndTime": 1609988362.281,
           "target": {
               "securityProfileName": "security-profile-for-smart-lights",
               "behaviorName": "num-messages-sent-ml-behavior"
           },
           "violationEventOccurrenceRange": {
               "startTime": 1609986633.0,
               "endTime": 1609987833.0
           },
           "onlyActiveViolationsIncluded": true,
           "suppressedAlertsIncluded": true,
           "actionsDefinition": [
               {
                   "name": "detect_mitigation_action",
                   "id": "5939e3a0-bf4c-44bb-a547-1ab59ffe67c3",
                   "roleArn": "arn:aws:iam::123456789012:role/MitigatioActionValidRole",
                   "actionParams": {
                       "addThingsToThingGroupParams": {
                           "thingGroupNames": [
                               "ThingGroupForDetectMitigationAction"
                           ],
                           "overrideDynamicGroups": false
                       }
                   }
               }
           ],
           "taskStatistics": {
               "actionsExecuted": 0,
               "actionsSkipped": 0,
               "actionsFailed": 0
           }
       }
   }
   ```

1. （可选）要获取缓解操作任务的列表，请使用 `[list-detect-mitigation-actions-tasks](https://docs.aws.amazon.com/cli/latest/reference/iot/list-detect-mitigation-actions-tasks.html)` 命令。

   ```
   aws iot list-detect-mitigation-actions-tasks \
       --start-time 1609985315 \
       --end-time 1609988915 \
       --max-items 5 \
       --page-size 4
   ```

   输出：

   ```
   {
       "tasks": [
           {
               "taskId": "taskIdForMitigationAction",
               "taskStatus": "SUCCESSFUL",
               "taskStartTime": 1609988361.224,
               "taskEndTime": 1609988362.281,
               "target": {
                   "securityProfileName": "security-profile-for-smart-lights",
                   "behaviorName": "num-messages-sent-ml-behavior"
               },
               "violationEventOccurrenceRange": {
                   "startTime": 1609986633.0,
                   "endTime": 1609987833.0
               },
               "onlyActiveViolationsIncluded": true,
               "suppressedAlertsIncluded": true,
               "actionsDefinition": [
                   {
                       "name": "detect_mitigation_action",
                       "id": "5939e3a0-bf4c-44bb-a547-1ab59ffe67c3",
                       "roleArn": "arn:aws:iam::123456789012:role/MitigatioActionValidRole",
                       "actionParams": {
                           "addThingsToThingGroupParams": {
                               "thingGroupNames": [
                                   "ThingGroupForDetectMitigationAction"
                               ],
                               "overrideDynamicGroups": false
                           }
                       }
                   }
               ],
               "taskStatistics": {
                   "actionsExecuted": 0,
                   "actionsSkipped": 0,
                   "actionsFailed": 0
               }
           }
       ]
   }
   ```

1. （可选）要取消缓解操作任务，请使用 `[cancel-detect-mitigation-actions-task](https://docs.aws.amazon.com/cli/latest/reference/iot/cancel-detect-mitigation-actions-task.html)` 命令。

   ```
   aws iot cancel-detect-mitigation-actions-task \
       --task-id taskIdForMitigationAction
   ```

   输出：

   无。