【发布时间】:2023-03-14 07:18:01
【问题描述】:
我一直在尝试为 Zabbix 实现一个警报脚本。 Zabbix 出于某种原因尝试在 Shell 中运行脚本,而脚本是用 Bash 编写的。
#!/bin/bash
# Slack incoming web-hook URL and user name
url='https://hooks.slack.com/services/this/is/my/webhook/' # example: https://hooks.slack.com/services/QW3R7Y/D34DC0D3/BCADFGabcDEF123
username='Zabbix Notification System'
## Values received by this script:
# To = $1 (Slack channel or user to send the message to, specified in the Zabbix web interface; "@username" or "#channel")
# Subject = $2 (usually either PROBLEM or RECOVERY/OK)
# Message = $3 (whatever message the Zabbix action sends, preferably something like "Zabbix server is unreachable for 5 minutes - Zabbix server (127.0.0.1)")
# Get the Slack channel or user ($1) and Zabbix subject ($2 - hopefully either PROBLEM or RECOVERY/OK)
to="$1"
subject="$2"
# Change message emoji depending on the subject - smile (RECOVERY/OK), frowning (PROBLEM), or ghost (for everything else)
recoversub='^RECOVER(Y|ED)?$'
if [[ "$subject" =~ ${recoversub} ]]; then
emoji=':smile:'
elif [ "$subject" == 'OK' ]; then
emoji=':smile:'
elif [ "$subject" == 'PROBLEM' ]; then
emoji=':frowning:'
else
emoji=':ghost:'
fi
# The message that we want to send to Slack is the "subject" value ($2 / $subject - that we got earlier)
# followed by the message that Zabbix actually sent us ($3)
message="${subject}: $3"
# Build our JSON payload and send it as a POST request to the Slack incoming web-hook URL
payload="payload={\"channel\": \"${to//\"/\\\"}\", \"username\": \"${username//\"/\\\"}\", \"text\": \"${message//\"/\\\"}\", \"icon_emoji\": \"${emoji}\"}"
curl -m 5 --data-urlencode "${payload}" $url -A "https://hooks.slack.com/services/this/is/my/web/hook"
~
当我使用“bash slack.sh”在本地运行脚本时,它会发送一个空通知,我会在 Slack 中收到该通知。 当我使用“sh slack.sh”在本地运行脚本时,出现以下错误。
slack.sh: 19: slack.sh: [[: not found
slack.sh: 21: [: unexpected operator
slack.sh: 23: [: unexpected operator
slack.sh: 34: slack.sh: Bad substitution
感谢您的帮助。
【问题讨论】:
-
如果
Zabbix需要一个POSIX shell 脚本,那么你必须编写一个POSIX shell 脚本,而[[不是由POSIX 定义的。您是否可以将Zabbix配置为使用不同的shell 是另一个问题。 (如果Zabbix只需要一个可执行文件,那么@bishop 就有答案。) -
(@bishop 删除了他的评论,其中建议使用
#!/bin/bash而不是# !/bin/bash。) -
根据Zabbix网站; “Zabbix 中的正则表达式支持已从 POSIX 扩展正则表达式切换到 Perl 兼容正则表达式 (PCRE),以增强正则表达式和与前端的一致性。”我已经考虑(并尝试过)删除'[['并将其替换为单个'[',但这无济于事。
-
我不认为 Zabbix 中的正则表达式支持是相关的;这是一个 shell 脚本,或者您使用的是
bash,在这种情况下,=~需要一个 POSIX 正则表达式,或者该脚本由/bin/sh(一个 POSIX 兼容的 shell)执行并且不支持正则表达式完全匹配。 -
但请注意,在 shell 中进行正则表达式匹配非常简单:
if echo "$string_to_match" | grep "$pattern" > /dev/null; then ...效果很好。