python&powershell&shell三種方式實現微信報警

運維中你們會碰到異常須要告警時,目前流行方式是微信告警,根據運維精簡化須要(不安裝沒必要要應用,通常應用服務器默認安裝的腳本語言執行,省去過多安裝過程),作了如下三種語言腳本供你們參考:
實現功能:給微信發短信,三個參數,第一個參數爲羣發(值爲1)仍是單獨發送(值爲2);第二個參數爲用戶ID,如羣發,值爲組id號,如網上交易組id爲2,,如單獨發送,值爲帳號,如道然id爲daoran,無大小寫區分。
一、python你們最熟悉的語言,跨平臺,但須要安裝包。
#!/usr/bin/pythonpython

-- coding: utf-8 --

import requests
import json
import sys
if sys.getdefaultencoding() != 'utf-8':
reload(sys)
sys.setdefaultencoding('utf-8')linux

corpid = "**"
corpsecret = "****"
agentid = 1000002web

def getToken():
url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s" % (corpid, corpsecret)
r = requests.get(url)
res = r.json()
return res.get("access_token")shell

def sendAlert(category, dest, alert):
token = getToken()
url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % token
message = {}json

if str(category) == '1':
    message['toparty'] = str(dest)
elif str(category) == '2':
    message['touser'] = str(dest)

message['msgtype'] = "text"
message['agentid'] = agentid
text = {'content': alert}
message['text'] = text
message['safe'] = 0
print (message)
payload = json.dumps(message)
r = requests.post(url, data=payload)
print(r.text)

def help():
help = """
此腳本用於發送微信告警,可選擇發給某個組或我的
命令格式:wechat_alert.py [類別] [推送對象] [告警消息]
其中,類別參數爲1則發送給組, 爲2則發送給我的,
推送對象在類別爲組時填組ID, 類別爲我的時填我的ID
例如:發送告警消息給安全組成員 wechat_alert.py 1 2 "alert test"
"""
print (help)windows

def main():
if len(sys.argv) < 2:
help()
sys.exit(1)
else:
category = sys.argv[1]
dest = sys.argv[2]
alert = sys.argv[3]
sendAlert(category, dest, alert)centos

if name == 'main':
main()api

以上腳本保存爲webchat_alert.py,在windows2012及centos6.9上運行命令python webchat_alert.py 2 liuyousheng 「my name is liuyousheng」經過。
二、powershell,默認windows2012已經安裝
function send-WeChat {
Param(
[String]$CateGory,
[String]$UserId,
[String]$Content
)安全

#微信基礎參數配置
$corpid="****" #微信企業號的開發者ID
$pwd="**" #微信企業號的開發者密碼
$AgentId="1000002" #代理IDbash

$auth_string = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$corpid&corpsecret=$pwd"
$auth_values = Invoke-RestMethod $auth_string
$token = $auth_values.access_token
$leibie=[Int]$CateGory
$body = "{}"
if ($leibie -eq 1) {
$body="{
"toparty":"$UserId",
"agentid":"$AgentId",
"text":{
"content":"$content"
},
"msgtype":"text",
"safe":"0"
}"
}

elseif ($leibie -eq 2) {
$body="{
"touser":"$UserId",
"agentid":"$AgentId",
"text":{
"content":"$content"
},
"msgtype":"text",
"safe":"0"
}"
}
#$body
$To_CN=[System.Text.Encoding]::UTF8.GetBytes($body)
Invoke-RestMethod "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$token" -ContentType "application/json" -Method Post -Body $To_CN
}

##調用示例1,發給我的
#$CateGory="2" #類別1爲組,2爲我的
#$UserId="daoran" #用戶組ID 當類別未1是,此出爲組ID,當類別爲2時,爲用戶名
#$content="my name is daoran" #發送的文本信息
#send-WeChat -CateGory $CateGory -UserId $UserId -Content $content

##調用示例2,發給組員
#$CateGory="1" #類別1爲組,2爲我的
#$UserId="2" #用戶組ID 當類別未1是,此出爲組ID,當類別爲2時,爲用戶名
#$content="my name is wsjy" #發送的文本信息
#send-WeChat -CateGory $CateGory -UserId $UserId -Content $content
以上腳本保存爲webchat-alert.ps1,在windows2012下測試經過。
三、shell腳本,linux下默默都有。
#!/bin/bash

-- coding: utf-8 --

CropID='****'
Secret='*****'
GURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$CropID&corpsecret=$Secret"
Gtoken=$(/usr/bin/curl -s -G $GURL | awk -F \" '{print $10}')
PURL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$Gtoken"function body() {local int AppID=1000002 # 企業號中的應用idlocal PartyID=$1 # 部門id,定義了範圍,組內成員均可接收到消息local UserID=$2 # 部門成員id,zabbix中定義的微信接收者local Msg=$3 # 過濾出zabbix中傳遞的第三個參數printf '{\n'if [ $PartyID == '1' ]thenprintf '\t"toparty": "'$UserID'",\n'elif [ $PartyID == '2' ]thenprintf '\t"touser": "'$UserID'",\n'elseprintf ''fiprintf '\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'}curl --data-ascii "$(body $1 $2 $3)" $PURLprintf '\n'echo "over!"以上腳本保存爲webchat-alert.sh,在centos6.9下執行./webchat-alert.sh 2 daoran "my name is daoran"測試經過。

相關文章
相關標籤/搜索