[英]post json message to slack channel using python
我的目標是將安全中心發現與松弛通道集成。 為此,我創建了 aws 事件橋規則,將目標作為 SNS 主題,並將 AWS lambda 作為訂閱。 我已經推薦了這個博客 - https://aws.amazon.com/premiumsupport/knowledge-center/sns-lambda-webhooks-chime-slack-teams/
Lambda 是用 python 3.8 版編寫的。
import urllib3
import json
http = urllib3.PoolManager()
def lambda_handler(event, context):
url = "https://hooks.slack.com/services/********"
msg = {
"channel": "#project-lambda",
#"username": "WEBHOOK_USERNAME",
"text": event['Records'][0]['Sns']['Message'],
"icon_emoji": ""
}
encoded_msg = json.dumps(msg).encode('utf-8')
resp = http.request('POST',url, body=encoded_msg)
print({
"message": event['Records'][0]['Sns']['Message'],
"status_code": resp.status,
"response": resp.data
})
使用上面的代碼,只要觸發事件規則,我就可以從 SNS 接收松弛通道上的消息,但這些消息不是可讀格式。
松弛消息輸出;
{"version":"0","id":"932c45e8-fdca-c2c0-25d7-7256467","detail-type":"Security Hub Findings - Imported","source":"aws.securityhub","account":"12345678","time":"2022-03-22T12:38:18Z","region":"us-east-1","resources":["arn:aws:securityhub:us-east-1::product/aws/securityhub/arn:aws:securityhub:us-east-1:12345678:subscription/aws-foundational-security-best-practices/v/1.0.0/S3.4/finding/5b012768-4639-4e5d-bd3c-34213876uh"],"detail":{"findings":[{"ProductArn":"arn:aws:securityhub:us-east-1::product/aws/securityhub","Types":["Software and Configuration Checks/Industry and Regulatory Standards/AWS-Foundational-Security-Best-Practices"],"Description":"This AWS control checks that your Amazon S3 bucket either has Amazon S3 default encryption enabled or that the S3 bucket policy explicitly denies put-object requests without server side encryption.","Compliance":{"Status":"FAILED"},
<<<< output omitted >>>>
相反,我希望輸出以以下 json 格式顯示;
{
"version": "0",
"id": "932c45e8-fdca-c2c0-25d7-0cc89d76d336",
"detail-type": "Security Hub Findings - Imported",
"source": "aws.securityhub",
"account": "858703963673",
"time": "2022-03-22T12:38:18Z",
"region": "us-east-1",
"resources": ["arn:aws:securityhub:us-east-1::product/aws/securityhub/arn:aws:securityhub:us-east-1:858703963673:subscription/aws-foundational-security-best-practices/v/1.0.0/S3.4/finding/5b012768-4639-4e5d-bd3c-8ef4439540d6"],
"detail": {
"findings": [{
"ProductArn": "arn:aws:securityhub:us-east-1::product/aws/securityhub",
"Types": ["Software and Configuration Checks/Industry and Regulatory Standards/AWS-Foundational-Security-Best-Practices"],
"Description": "This AWS control checks that your Amazon S3 bucket either has Amazon S3 default encryption enabled or that the S3 bucket policy explicitly denies put-object requests without server side encryption.",
"Compliance": {
"Status": "FAILED"
},
<<<< output omitted >>>>
我相信這個 webhook 應用程序不支持 json 格式,但是有沒有辦法在 json 的 slack 通道上發布輸出?
您可以在有效負載中使用"link_names": True :
slack_data = {
'text': _text,
"icon_emoji": self._icon,
"username": _sender,
"link_names": True
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.