{"errcode":40014,"errmsg":"invalid access_token"} 微信報警腳本,坑已解決——shell語言

CropID='    '
Secret='    '
GURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$CropID&corpsecret=$Secret"

#get acccess_token
token=$(/usr/bin/curl -s -G $GURL| awk -F\" '{print $4}')
PURL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$token"
#
function body() {
local int AppID=1000004                        #企業號中的應用id
local UserID="touser"                        #部門成員id,zabbix中定義的微信接收者
local PartyID=1                           #部門id,定義了範圍,組內成員均可接收到消息
local Msg=$(echo "$@" | cut -d" " -f3-)   #過濾出zabbix傳遞的第三個參數
printf '{\n'
printf '\t"touser": "'"$UserID"\"",\n"
printf '\t"toparty": "'"$PartyID"\"",\n"
printf '\t"msgtype": "text",\n'
printf '\t"agentid": "'" $AppID "\"",\n"
printf '\t"text": {\n'
printf '\t\t"content": "'"$Msg"\""\n"
printf '\t},\n'
printf '\t"safe":"0"\n'
printf '}\n'
}
/usr/bin/curl --data-ascii "$(body $! $2 $3)" $PURL

上面的demo是在度娘上常見的,正常調用微信api會返回: 輸入圖片說明shell

那麼問題出在哪裏呢? // 請從新查看上面demo 配置完成CropID 以及 Secret以後咱們的GURL是正常的 能夠打印下查看api

GURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$CropID&corpsecret=$Secret"
echo $GURL
#get acccess_token
token=$(/usr/bin/curl -s -G $GURL| awk -F\" '{print $4}')

打印結果 輸入圖片說明 獲取到GURL以後腳本輸入服務器

curl -v 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwc******bf4&corpsecret=xEhgjy******5tQ'

輸入圖片說明

在這裏咱們能夠看到curl請求URL HTTP返回200請求是成功的,access_token也是可以正常獲取到。 前方高能:坑來了, 根據上方的demo,咱們在輸出下一句微信

token=$(/usr/bin/curl -s -G $GURL| awk -F\" '{print $4}')
echo $token

返回: 輸入圖片說明 上圖咱們能夠看到CURL請求後,shell awk正則匹配篩選後的值並非先前咱們所獲取到的access_tokencurl

GURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$CropID&corpsecret=$Secret"
#get acccess_token
token=$(/usr/bin/curl -s -G $GURL| awk -F\" '{print $4}')
echo $token
PURL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$token"

相信看到這裏你們已經明確了,curl是能夠正常請求,問題就出在awk正則上, shell awk正則具體用法你們能夠自行百度。 這裏提供出正確的正則匹配。url

GURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$CropID&corpsecret=$Secret"
#get acccess_token
Gtoken=$(/usr/bin/curl -s -G $GURL)
a=`echo $Gtoken |awk -F ':"' '{print $3}'`
token=`echo $a |awk -F '".' '{print $1}'`
PURL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$token"

將上面代碼替換到開頭的demo中,你們也能夠自行echo查看輸出內容。 正則是一次次篩選的,掌握後能夠進行一次正則匹配。 替換好的代碼咱們再來調用: 輸入圖片說明 輸入圖片說明 能夠看到微信已經能夠正常接受到服務器發送的信息。code

但願能夠幫助到你們再用demo的同時掌握其中奧妙而不是一味盲用。 高手勿噴。token

相關文章
相關標籤/搜索