头图:https://cdn.naraku.cn/imgs/Github_CVE_Wechat-0.jpg
摘要:公众号上看到的小脚本,拿下来做了一些修改,当Python练手啦~
前言
最近在@洛米唯熊公众号中看到一篇对Github新CVE的监控并推送到微信的文章,其结合Github的API获取CVE的相关数据,并通过itchat库推送到微信。但是使用这个库登录的微信时,是不能再在PC端登录微信的,否则会被挤下线。虽然可以使用小号微信来运行脚本,但是感觉还是不方便,因为偶尔小号也可能会需要登录PC端。因此对这部分代码进行了改写,使用Server酱来进行消息的推送。
数据获取
这里进行了一点改动,将获取到的数据通过
JSON库转换成字典类型返回,便于后续匹配。并通过CVE-{当前年份}来获取今年的CVE,这样就不用每年都改了(如果这个脚本能跑上几年…)import jsonimport requestsdef getNews():year = time.strftime("%Y", time.localtime(time.time()))try:api = f"https://api.github.com/search/repositories?q=CVE-{year}&sort=updated"response = requests.get(api).textdata = json.loads(response)return dataexcept Exception as e:print(e, "Github链接不通")if __name__ == '__main__':data = getNews()
数据解析
获取到的数据使用
itemgetter()函数进行关键字排序,通过比较total的变化来判断是否需要推送- 参考:Python3 - 通过关键字排序字典列表
from operator import itemgetterdef parseData(index):item = items[index]cve_name = item['name']cve_url = item['svn_url']cve_des = item['description']if not cve_des: # 描述为空时会返回Nonecve_des = "Null"content = f"{cve_name}: {cve_url}, Des: {cve_des}"return contentif __name__ == '__main__':total = 0 # 初始化为0data = getNews()if total != data['total_count']:total = data['total_count']items = sorted(data['items'], key=itemgetter('id'), reverse=True) # 根据items中的id进行排序content = parseData(0) # 返回最新的1条
推送信息
 
- 参考:Python3 - 通过关键字排序字典列表
 使用Server酱很轻松就可以实现消息的推送
def sendMsg(content):send_url = f"https://sc.ftqq.com/{SCKEY}.send"data = {"text": "CVE监控提醒","desp": content}r = requests.post(send_url, data=data)if __name__ == '__main__':SCKEY = "Your_SCKEY"total = 0 # 初始化data = getDic()if total != data['total_count']:total = data['total_count']items = sorted(data['items'], key=itemgetter('id'), reverse=True) # 根据items中的id进行排序content = parseData(0) # 返回最新的1条sendMsg(content)
推送效果
完整代码
最后引入
time()函数,每隔一段时间运行一次即可# -*- coding:utf-8 -*-"""@Author: Naraku@File: Github_CVE_Wechat.py"""import timeimport jsonimport requestsfrom operator import itemgetterdef getNews():year = time.strftime("%Y", time.localtime(time.time()))try:api = f"https://api.github.com/search/repositories?q=CVE-{year}&sort=updated"response = requests.get(api).textdata = json.loads(response)return dataexcept Exception as e:print(e, "Github链接不通")def parseData(index):item = items[index]cve_name = item['name']cve_url = item['svn_url']cve_des = item['description']if not cve_des: # 描述为空时会返回Nonecve_des = "Null"content = f"{cve_name}: {cve_url}, Des: {cve_des}"return contentdef sendMsg(content):send_url = f"https://sc.ftqq.com/{SCKEY}.send"data = {"text": "CVE监控提醒","desp": content}r = requests.post(send_url, data=data)if __name__ == '__main__':SCKEY = "Your_SCKEY"total = 0 # 初始化while True:data = getNews()if total != data['total_count']:total = data['total_count']items = sorted(data['items'], key=itemgetter('id'), reverse=True) # 根据items中的id进行排序content = parseData(0) # 返回最新的1条sendMsg(content)time.sleep(60)

