#!/bin/bash ### script name weixin.sh ### send messages from weixin for zabbix monitor ### jack ### 2016-7-18 ### usage: curl -s -G url 获取acessToken ### curl --data url 传送凭证调用企业号接口 ### zabbix 会传送三个参数给脚本,$1 是消息接收账号,$2 报警标题, $3 报警内容 CropID='111' Secret='3333' GURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$CropID&corpsecret=$Secret" Gtoken=$(/usr/bin/curl -s -G $GURL | awk -F '"' '{print $4}') now_time=$(date -d now) now_timestamp=$(date -d "${now_time}" +%s) options=$[2*60*60] token_file='/tmp/token_file.txt' PURL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$Gtoken" LOG_FILE='/tmp/weixin_log.txt' function logMessageToFile(){ echo "[ $1 ] - ["$(date "+%Y-%m-%d %H:%M:%S")"] - $2" >> $LOG_FILE } function create_tokenfile(){ echo "${now_time} > ${Gtoken}" > ${token_file} } function get_Gtoken(){ GURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$CropID&corpsecret=$Secret" Gtoken=$(/usr/bin/curl -s -G $GURL | awk -F '"' '{print $4}') } function check_token(){ if [ -f "${token_file}" ]; then file_token=$(awk -F '>' '{print $2}' ${token_file}) file_time=$(awk -F '>' '{print $1}' ${token_file}) file_timestamp=$(date -d "${file_time}" +%s) time_difference=$[${now_timestamp}-${file_timestamp}] if [ "${time_difference}" -gt "${options}" ]; then get_Gtoken create_tokenfile logMessageToFile "INFO" "上次token是: ${file_token},到现在过了${time_difference} 秒, 新的token是:${Gtoken}" else logMessageToFile "INFO" "not need update the token, use old token ${file_token} 到现在过了${time_difference} 秒" Gtoken=$(echo ${file_token}) fi else get_Gtoken logMessageToFile "INFO" "the token_file : ${token_file} not exsits ,will create it . 到现在过了${time_difference} 秒" create_tokenfile fi } function body(){ local int AppID=1 # 企业号中的应用ID local UserID="@all" # 部门成员id,zabbix中定义的微信接受者 local PartyID=2 # 部门id,定义了范围,组内成员都可接收到消息 local Msg=$(echo "$@" | cut -d " " -f3-) # 过滤出zabbix中传递的第三个参数 printf '{ ' printf ' "touser":"'"$UserID""", " printf ' "toparty":"'"$PartyID""", " printf ' "msgtype": "text",'" " printf ' "agentid":'$AppID\," " printf ' "text":{ ' printf ' "content":"'"$Msg"" printf ' }, ' printf ' "safe":"0" ' printf '} ' } check_token /usr/bin/curl --data-ascii "$(body $1 $2 $3)" $PURL