0x01 背景
用到就学一下,分享一下。
0x02 创建自定义机器人
群设置 –> 智能群助手 –> 添加机器人 –> 自定义机器人

设置的关键词的意思是含有关键词的消息机器人才会发送
所以py脚本中dingding发送接口要含此关键词

记一下access_token
0x03 编写cna脚本
写一个cna
检测到新的主机连接,就运行一遍py脚本发送至钉钉
cna代码如下
cs-dd.cna
1 2 3 4 5 6 7 8 9 10 11
| on beacon_initial { println("Initial Beacon Checkin: " . $1 . " PID: " . beacon_info($1, "pid")); local('$internalIP $computerName $userName'); $internalIP = replace(beacon_info($1, "external"), " ", "_"); $computerName = replace(beacon_info($1, "computer"), " ", "_"); $userName = replace(beacon_info($1, "user"), " ", "_"); $cmd = 'python3 /home/m2/CS4.4/cs_remind_dingding.py --computername ' . $computerName . " --internalip " . $internalIP . " --username " . $userName; println("Sending dingding Notification: " . $cmd); exec($cmd); println('success'); }
|
当有主机上线时,获取参数发给py脚本,py脚本执行将主机信息发送给钉钉(执行py脚本那里使用绝对路径)
0x04 编写python脚本
python脚本接收computername、internalip、username三个参数发送给钉钉
python脚本代码如下
cs_remind_dingding.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| #!/usr/bin/env python # -*- coding:utf8 -*- # coding=utf-8 # coding=gbk
import os import time import requests from argparse import ArgumentParser
def dingdingsend(text): # 钉钉发信模块 dingdingurl = 'https://oapi.dingtalk.com/robot/send?access_token=填写刚才记录的access_token' headers = { 'Content-Type': 'application/json', } data = {"msgtype": "text", "text": { "content": text }, "at":{ "atMobiles":[ "13838888888" #艾特提醒的人 ] }, } try: r = requests.post(dingdingurl, json=data, headers=headers) except Exception as e: print(e)
if __name__ == '__main__': arg=ArgumentParser(description='cs bot By m2') arg.add_argument("-c", "--computername", help="computername; Example:mzzd") arg.add_argument("-t", "--internalip", help="Target ip; Example:xxx.xxx.xxx.xxx") arg.add_argument("-u", "--username", help="username; Example:administrator")
args=arg.parse_args() computername=args.computername ip=args.internalip username=args.username dingdingsend("#cs主机上线提醒\n主机名称:{}\n主机IP:{}\n用户名:{}".format(computername,ip,username))
|
将cna和py脚本放在服务器cs根目录
赋权执行
1
| ./agscript 42.xxx.xxx.xxx 50050 m2 xxxxx ./cs-dd.cna #cs服务器密码
|

本地测试可以看到上线秒提醒

测试没有问题用nohup后台运行cna即可
1
| nohup ./agscript 42.xxx.xxx.xxx 50050 m2 xxxxx ./cs-dd.cna >>/dev/null 2>&1 &
|
