[comment]: # ({923acd1d-923acd1d})
# 5 媒体类型

[comment]: # ({/923acd1d-923acd1d})

[comment]: # ({e0b517c9-e0b517c9})
#### 概述

媒体类型是与所有相关objects和object关系相关联的[exported](/manual/xml_export_import)

[comment]: # ({/e0b517c9-e0b517c9})

[comment]: # ({7e0a36b8-7e0a36b8})
#### 导出

要export媒介类型，请执行以下操作：

- 前往：*管理* → *媒介类型*
-   勾选要export的媒介类型复选框
- 点击列表下方的*导出*

![](../../../assets/en/manual/xml_export_import/export_mediatypes.png)

根据所选格式，媒体类型将被导出到本地
file 使用默认名称:

-   *zabbix\_export\_mediatypes.yaml* - YAML格式的export（默认选项）
    对于export
-   *zabbix\_export\_mediatypes.xml* - XML格式 export
-   *zabbix\_export\_mediatypes.json* - JSON格式 export

[comment]: # ({/7e0a36b8-7e0a36b8})

[comment]: # ({7f828bf2-7f828bf2})
#### 导入

要import媒介类型，请执行以下操作：

-   前往：*管理* → *媒介类型*
-   点击右侧的*导入*
-   选择要import的file
-   在import规则中标记所需选项
-   点击*导入*

![](../../../assets/en/manual/xml_export_import/import_media.png)

前端将显示import成功或失败的消息。

导入规则：

| 规则 | 描述 |
|----|-----------|
| *更新现有* | 现有元素将使用import的file中的数据更新。否则将不会更新。 |
| *创建新* | import将使用import的file中的数据添加新元素。否则不会添加。 |
| *删除缺失* | import将移除import的file中不存在的现有元素。否则不会移除。 |

[comment]: # ({/7f828bf2-7f828bf2})

[comment]: # ({b6cd9f78-480f411a})
#### 导出格式

导出为YAML格式:

```yaml
zabbix_export:
  version: '6.0'
  date: '2021-08-31T13:34:17Z'
  media_types:
    - name: Pushover
      type: WEBHOOK
      parameters:
        - name: endpoint
          value: 'https://api.pushover.net/1/messages.json'
        - name: eventid
          value: '{EVENT.ID}'
        - name: event_nseverity
          value: '{EVENT.NSEVERITY}'
        - name: event_source
          value: '{EVENT.SOURCE}'
        - name: event_value
          value: '{EVENT.VALUE}'
        - name: expire
          value: '1200'
        - name: message
          value: '{ALERT.MESSAGE}'
        - name: priority_average
          value: '0'
        - name: priority_default
          value: '0'
        - name: priority_disaster
          value: '0'
        - name: priority_high
          value: '0'
        - name: priority_information
          value: '0'
        - name: priority_not_classified
          value: '0'
        - name: priority_warning
          value: '0'
        - name: retry
          value: '60'
        - name: title
          value: '{ALERT.SUBJECT}'
        - name: token
          value: '<PUSHOVER TOKEN HERE>'
        - name: triggerid
          value: '{TRIGGER.ID}'
        - name: url
          value: '{$ZABBIX.URL}'
        - name: url_title
          value: Zabbix
        - name: user
          value: '{ALERT.SENDTO}'
      max_sessions: '0'
      script: |
        try {
            var params = JSON.parse(value),
                request = new HttpRequest(),
                data,
                response,
                severities = [
                    {name: 'not_classified', color: '#97AAB3'},
                    {name: 'information', color: '#7499FF'},
                    {name: 'warning', color: '#FFC859'},
                    {name: 'average', color: '#FFA059'},
                    {name: 'high', color: '#E97659'},
                    {name: 'disaster', color: '#E45959'},
                    {name: 'resolved', color: '#009900'},
                    {name: 'default', color: '#000000'}
                ],
                priority;
        
            if (typeof params.HTTPProxy === 'string' && params.HTTPProxy.trim() !== '') {
                request.setProxy(params.HTTPProxy);
            }
        
            if ([0, 1, 2, 3].indexOf(parseInt(params.event_source)) === -1) {
                throw 'Incorrect "event_source" parameter given: "' + params.event_source + '".\nMust be 0-3.';
            }
        
            if (params.event_value !== '0' && params.event_value !== '1'
                && (params.event_source === '0' || params.event_source === '3')) {
                throw 'Incorrect "event_value" parameter given: ' + params.event_value + '\nMust be 0 or 1.';
            }
        
            if ([0, 1, 2, 3, 4, 5].indexOf(parseInt(params.event_nseverity)) === -1) {
                params.event_nseverity = '7';
            }
        
            if (params.event_value === '0') {
                params.event_nseverity = '6';
            }
        
            priority = params['priority_' + severities[params.event_nseverity].name] || params.priority_default;
        
            if (isNaN(priority) || priority < -2 || priority > 2) {
                throw '"priority" should be -2..2';
            }
        
            if (params.event_source === '0' && isNaN(params.triggerid)) {
                throw 'field "triggerid" is not a number';
            }
        
            if (isNaN(params.eventid)) {
                throw 'field "eventid" is not a number';
            }
        
            if (typeof params.message !== 'string' || params.message.trim() === '') {
                throw 'field "message" cannot be empty';
            }
        
            data = {
                token: params.token,
                user: params.user,
                title: params.title,
                message: params.message,
                url: (params.event_source === '0') 
                    ? params.url + '/tr_events.php?triggerid=' + params.triggerid + '&eventid=' + params.eventid
                    : params.url,
                url_title: params.url_title,
                priority: priority
            };
        
            if (priority == 2) {
                if (isNaN(params.retry) || params.retry < 30) {
                    throw 'field "retry" should be a number with value of at least 30 if "priority" is set to 2';
                }
        
                if (isNaN(params.expire) || params.expire > 10800) {
                    throw 'field "expire" should be a number with value of at most 10800 if "priority" is set to 2';
                }
        
                data.retry = params.retry;
                data.expire = params.expire;
            }
        
            data = JSON.stringify(data);
            Zabbix.log(4, '[ Pushover Webhook ] Sending request: ' + params.endpoint + '\n' + data);
        
            request.addHeader('Content-Type: application/json');
            response = request.post(params.endpoint, data);
        
            Zabbix.log(4, '[ Pushover Webhook ] Received response with status code ' + request.getStatus() + '\n' + response);
        
            if (response !== null) {
                try {
                    response = JSON.parse(response);
                }
                catch (error) {
                    Zabbix.log(4, '[ Pushover Webhook ] Failed to parse response received from Pushover');
                    response = null;
                }
            }
        
            if (request.getStatus() != 200 || response === null || typeof response !== 'object' || response.status !== 1) {
                if (response !== null && typeof response === 'object' && typeof response.errors === 'object'
                        && typeof response.errors[0] === 'string') {
                    throw response.errors[0];
                }
                else {
                    throw 'Unknown error. Check debug log for more information.';
                }
            }
        
            return 'OK';
        }
        catch (error) {
            Zabbix.log(4, '[ Pushover Webhook ] Pushover notification failed: ' + error);
            throw 'Pushover notification failed: ' + error;
        }
      description: |
        Please refer to setup guide here: https://git.zabbix.com/projects/ZBX/repos/zabbix/browse/templates/media/pushover
        
        Set token parameter with to your Pushover application key.
        When assigning Pushover media to the Zabbix user - add user key into send to field.
      message_templates:
        - event_source: TRIGGERS
          operation_mode: PROBLEM
          subject: 'Problem: {EVENT.NAME}'
          message: |
            Problem started at {EVENT.TIME} on {EVENT.DATE}
            Problem name: {EVENT.NAME}
            Host: {HOST.NAME}
            Severity: {EVENT.SEVERITY}
            Operational data: {EVENT.OPDATA}
            Original problem ID: {EVENT.ID}
            {TRIGGER.URL}
        - event_source: TRIGGERS
          operation_mode: RECOVERY
          subject: 'Resolved in {EVENT.DURATION}: {EVENT.NAME}'
          message: |
            Problem has been resolved at {EVENT.RECOVERY.TIME} on {EVENT.RECOVERY.DATE}
            Problem name: {EVENT.NAME}
            Problem duration: {EVENT.DURATION}
            Host: {HOST.NAME}
            Severity: {EVENT.SEVERITY}
            Original problem ID: {EVENT.ID}
            {TRIGGER.URL}
        - event_source: TRIGGERS
          operation_mode: UPDATE
          subject: 'Updated problem in {EVENT.AGE}: {EVENT.NAME}'
          message: |
            {USER.FULLNAME} {EVENT.UPDATE.ACTION} problem at {EVENT.UPDATE.DATE} {EVENT.UPDATE.TIME}.
            {EVENT.UPDATE.MESSAGE}
            
            Current problem status is {EVENT.STATUS}, age is {EVENT.AGE}, acknowledged: {EVENT.ACK.STATUS}.
        - event_source: DISCOVERY
          operation_mode: PROBLEM
          subject: 'Discovery: {DISCOVERY.DEVICE.STATUS} {DISCOVERY.DEVICE.IPADDRESS}'
          message: |
            Discovery rule: {DISCOVERY.RULE.NAME}
            
            Device IP: {DISCOVERY.DEVICE.IPADDRESS}
            Device DNS: {DISCOVERY.DEVICE.DNS}
            Device status: {DISCOVERY.DEVICE.STATUS}
            Device uptime: {DISCOVERY.DEVICE.UPTIME}
            
            Device service name: {DISCOVERY.SERVICE.NAME}
            Device service port: {DISCOVERY.SERVICE.PORT}
            Device service status: {DISCOVERY.SERVICE.STATUS}
            Device service uptime: {DISCOVERY.SERVICE.UPTIME}
        - event_source: AUTOREGISTRATION
          operation_mode: PROBLEM
          subject: 'Autoregistration: {HOST.HOST}'
          message: |
            Host name: {HOST.HOST}
            Host IP: {HOST.IP}
            Agent port: {HOST.PORT}
```

[comment]: # ({/b6cd9f78-480f411a})

[comment]: # ({2abe3918-f0190043})
#### 元素标签

元素标签值在下表中进行说明。

| 元素 | 元素属性 | 必填 | 类型 | 范围^**[1](#footnotes)**^ | 描述 |
|--|--|-|--|----|--------|
| media\_types |                  | \-       |      |                        | 媒体类型的根元素。 |
|         | name | x        | `string` |                        | 媒体类型名称。 |
|         | type | x        | `string` | 0 - EMAIL<br>1 - SMS<br>2 - SCRIPT<br>4 - WEBHOOK       | 媒体类型使用的传输方式。 |
|         | status | \-       | `string` | 0 - ENABLED (default)<br>1 - DISABLED       | 媒体类型是否启用。 |
|         | max\_sessions | \-       | `integer` | Possible values for SMS: 1 - (default)<br><br>Possible values for other media types: 0-100, 0 - unlimited       | 可并行处理的最大告警数量。 |
|         | attempts | \-       | `integer` | 1-10 (default: 3)       | 发送告警的最大尝试次数。 |
|         | attempt\_interval | \-       | `string` | 0-60s (default: 10s)       | 重试尝试之间的间隔。<br><br>接受带后缀的秒数和时间单位。 |
|         | description | \-       | `string` |                        | 媒体类型描述。 |
| message\_templates |                  | \-       |      |                        | 媒体类型消息模板的根元素。 |
|         | event\_source | x        | `string` | 0 - TRIGGERS<br>1 - DISCOVERY<br>2 - AUTOREGISTRATION<br>3 - INTERNAL<br>4 - SERVICE       | 事件来源。 |
|         | operation\_mode | x        | `string` | 0 - PROBLEM<br>1 - RECOVERY<br>2 - UPDATE       | 操作模式。 |
|         | subject | \-       | `string` |                        | 消息主题。 |
|         | message | \-       | `string` |                        | 消息正文。 |
| *Used only by email media type* | < | <        | < | <       | <           |
|         | smtp\_server | x        | `string` |                        | SMTP服务器。 |
|         | smtp\_port | \-       | `integer` | Default: 25       | 连接的SMTP服务器端口。 |
|         | smtp\_helo | x        | `string` |                        | SMTP helo。  |
|         | smtp\_email | x        | `string` |                        | 发送通知的电子邮件地址。 |
|         | smtp\_security | \-       | `string` | 0 - NONE (default)<br>1 - STARTTLS<br>2 - SSL\_OR\_TLS       | 使用的SMTP连接安全级别。 |
|         | smtp\_verify\_host | \-       | `string` | 0 - NO (default)<br>1 - YES       | SMTP的SSL验证主机。如果smtp\_security为STARTTLS或SSL\_OR\_TLS则为可选。 |
|         | smtp\_verify\_peer | \-       | `string` | 0 - NO (default)<br>1 - YES       | SMTP的SSL验证对等端。如果smtp\_security为STARTTLS或SSL\_OR\_TLS则为可选。 |
|         | smtp\_authentication | \-       | `string` | 0 - NONE (default)<br>1 - PASSWORD       | 使用的SMTP认证方法。 |
|         | username | \-       | `string` |                        | 用户名。   |
|         | password | \-       | `string` |                        | 认证密码。 |
|         | content\_type | \-       | `string` | 0 - TEXT<br>1 - HTML (default)       | 消息格式。 |
| *Used only by SMS media type* | < | <        | < | <       | <           |
|         | gsm\_modem | x        | `string` |                        | GSM调制解调器的串行设备名称。 |
| *Used only by script media type* | < | <        | < | <       | <           |
|         | script name | x        | `string` |                        | 脚本名称。 |
| parameters |                  | \-       |      |                        | 脚本参数的根元素。 |
| *Used only by webhook media type* | < | <        | < | <       | <           |
|         | script | x        | `string` |                        | 脚本。     |
|         | timeout | \-       | `string` | 1-60s (default: 30s)       | Javascript脚本HTTP请求超时间隔。 |
|         | process\_tags | \-       | `string` | 0 - NO (default)<br>1 - YES       | 是否处理返回的标签。 |
|         | show\_event\_menu | \-       | `string` | 0 - NO (default)<br>1 - YES       | 如果{EVENT.TAGS.\*}在event\_menu\_url和event\_menu\_name字段中成功解析，此字段表示事件菜单中是否存在条目。 |
|         | event\_menu\_url | \-       | `string` |                        | 事件菜单条目的URL。支持{EVENT.TAGS.\*}宏。 |
|         | event\_menu\_name | \-       | `string` |                        | 事件菜单条目的名称。支持{EVENT.TAGS.\*}宏。 |
| parameters |                  | \-       |      |                        | Webhook媒体类型参数的根元素。 |
|         | name | x        | `string` |                        | Webhook参数名称。 |
|         | value | \-       | `string` |                        | Webhook参数值。 |

[comment]: # ({/2abe3918-f0190043})

[comment]: # ({c1b1c6ab-c1b1c6ab})
##### 脚注

^**1**^ 对于string值，仅会导出string（例如"EMAIL"），不包含本表中使用的编号。本表中范围值（对应API值）的编号仅用于排序目的。

[comment]: # ({/c1b1c6ab-c1b1c6ab})
