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 }