python分析nginx日志结合阿里SLBAPI封IP

import subprocess

import re

import requests

import json

from paramiko import SSHClient, AutoAddPolicy

import hashlib

from aliyunsdkcore.client import AcsClient

from aliyunsdkcore.acs_exception.exceptions import ClientException

from aliyunsdkcore.acs_exception.exceptions import ServerException

from aliyunsdkslb.request.v20140515.AddAccessControlListEntryRequest import AddAccessControlListEntryRequest

#####微信通知模块

class send_weinxi():

    def __init__(self):

        self.params = {"corpid": "xxxxxxxx",

                      "corpsecret": "xxxxxxxxxxxxxx"}

        self.access_token = json.loads(

            requests.get('https://qyapi.weixin.qq.com/cgi-bin/gettoken', params=self.params).content.decode()).get("access_token")

    def send_weixin_msg(self, content):

        self.content = content

        message_card = json.dumps({

            "touser": "xxxxxxxxxx",

            "msgtype": "text",

            "agentid": 5,

            "text": {

                "content": """{}""".format(self.content)

            },

            "safe": 0

        })

        send_message = requests.post(

            "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}".format(self.access_token),

            data=message_card)

        return send_message.content

#####SLB API 增加恶意IP模块

class slb_add_ip():

    def __init__(self):

        self.Access_Key_ID = "xxxxxxxxxxxxxxxxx"

        self.Access_Key_Secret = "xxxxxxxxxxxxxxx"

        self.RegionId = 'cn-beijing'

    def client_add(self, entry, comment):

        entry = "{}/32".format(entry)

        comment = comment 

        client = AcsClient(self.Access_Key_ID, self.Access_Key_Secret, self.RegionId)

        request = AddAccessControlListEntryRequest()

        request.set_accept_format('json')

        request.set_action_name("AddAccessControlListEntry")

        request.set_AclId("acl-xxxxxx")

        request.set_AclEntrys([{"entry": entry, "comment": comment}])

        response = json.loads(client.do_action_with_exception(request), encoding='utf-8')

        return "OK"

######IP归属查询-已弃用,太频繁容易被封掉超时

def ip_api(ip):

    # params = { "lang": "zh-CN" }

    res = requests.get("http://ip-api.com/json/{}".format(ip))

    return json.loads(res.text)

client = SSHClient()

client.set_missing_host_key_policy(AutoAddPolicy())

client.connect(hostname='xxxxxxxx', port=xx, username='xx', password='xxxxxxxxxxxxx')

#p = subprocess.Popen('ssh -p xx xx@xxxxxxx "tail -F /opt/nginx/logs/access.log"', shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE, encoding='utf-8')

#ip_count = {

#    "ip_sha": {

#        "acc_count": ,

#        "contry": ''

#    }

#

#}

ip_total = dict()

send_wx = send_weinxi()

already_sended_ip = []

stdin, stdout, stderr = client.exec_command('tail -F /opt/nginx/logs/access.log')

while True:

#    print(ip_total)

#    line = p.stdout.readline()

    line = stdout.readline()

    if line:

        r = re.compile(r'"(?P<HTTP_X_REAL_IP>\d+.\d+.\d+.\d+)(?="\n)')

        xx = r.search(line)

        if xx:

            entry = xx.group(1)

            ip_sha = hashlib.sha256(entry.encode()).hexdigest()

            if ip_total.get(ip_sha):

                acc_count = ip_total.get(ip_sha).get('acc_count') + 1

                ip_total[ip_sha]['acc_count'] = acc_count

                if acc_count > 2000 and entry not in already_sended_ip:

                    comment = "deny"

                    already_sended_ip.append(entry)

                    add_ip_one = slb_add_ip()

                    add_ip_one.client_add(entry, comment)

                    send_wx.send_weixin_msg("Access Deny:\n{}".format(ip_total.get(ip_sha)))

            else:

                if entry != 'x.x.x.x' :

                    ip_total[ip_sha] = { "ip_info": entry, "acc_count": 1 }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • datetime是Python处理日期和时间的标准库。 获取当前日期和时间 我们先看如何获取当前日期和时间: >>...
    jbb_43b0阅读 1,041评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,967评论 19 139
  • Django知识点概述 Web应用 问题1:描述一个Web应用的工作流程。 问题2:描述项目的物理架构。(上图中补...
    领带衬有黄金阅读 735评论 0 1
  • A consultant is working on a Service Cloud implementation...
    柯小强阅读 30,328评论 0 5
  • 久违的晴天,家长会。 家长大会开好到教室时,离放学已经没多少时间了。班主任说已经安排了三个家长分享经验。 放学铃声...
    飘雪儿5阅读 7,573评论 16 22