这个脚本是基于wrk泛洪攻击的入侵检测
netstat -ant | wc -l 通过网络连接数如果看到异常说明被人搞了
可以从uptime、top多方面查看
实现效果图:
代码如下:
# -*- coding: utf-8 -*-
# @Time :
# @Author :
# @File : ids.py
# @Project : pythonProject1
# @脚本说明 :模拟IDS攻击
'''
基于wrk泛洪攻击的入侵检测
netstat -ant | wc -l 通过网络连接数如果看到异常说明有点东西
可以从uptime、top多方面查看主机的情况
'''
import os
def get_net():
'''检测网络连接数是否异常,是否>500'''
cmd = "netstat -ant |wc -l"
res = os.popen(cmd).read()
res = int((res.strip()))
return res
def get_uptime():
'''uptime 1min 0.2'''
cmd = "uptime | awk -F ',' '{print $4}'| awk '{print $3}'"
res = os.popen(cmd).read()
res = float((res.strip()))
return res
def get_top():
'''top -n 1 希望cpu的使用率 < 95'''
cmd = "top -n 1 | grep %Cpu | awk '{print $8}'"
res = os.popen(cmd).read()
res = float((res.strip()))
return res
def get_queue(n):
cmd = "ss -lnt | grep :520 | awk '{print $%s}'"%n
res = os.popen(cmd).read()
return (res.strip())
def get_que_diff():
after = int(get_queue(3))
before = int(get_queue(2))
diff = after-before
return (diff)
def get_net_recv():
cmd = "netstat -ant | grep SYN_RECV|wc -l"
res = os.popen(cmd).read()
res = int(res.strip())
return res
def get_netstat_ip():
cmd = "netstat -ant |grep :520 | grep SYN_RECV | awk '{print $5}' |awk -F ':' '{print $1}'|uniq"
ip = os.popen(cmd).read().strip()
return ip
def get_access_log(n):
try:
cmd = "tail -n %s /opt/lampp/logs/access_log|awk '{print $1}'"%n
res = os.popen(cmd).read()
ips = res.split('\n')
res = list(set(res.split('\n')))
res.remove('')
# res.remove('::1')
print('风险主机:', res)
c = ips.count(res[0])
print('数量:', c)
except:
pass
else:
return res,c
def deploy_unsafe(ip):
cmd = f"firewall-cmd --add-rich-rule='rule family=ipv4 source address={ip} reject'"
res = os.popen(cmd).read()
if 'success' in res:
print(f'{ip} was deployed successfully!')
if __name__ == '__main__':
while True:
net_count = get_net() # 网络连接数
uptime = get_uptime() # 1min CPU平均负载
top = get_top() # top CPU空闲占比
diff = get_que_diff() # 队列长度的差值
net_recv = get_net_recv() # 获取的是SYN RECV的连接数
ip = get_netstat_ip() # 获取SYN_RECV数量异常的IP
log = get_access_log(500) # 获取的是日志信息中的IP与其数量
print(f'当前的netstat 网络连接数为:{net_count}')
print(f'当前1min中的 CPU平均负载是{uptime}')
print(f'top资源中的CPU空闲占比为:{top}')
print(f'队列长度的差值为:{diff}')
print(f'当前的netstat 网络连接数为:{net_count}')
print(f'获取的是SYN_RECV的连接数为:{net_recv}')
print(f'获取SYN_RECV数量异常的IP为:{ip}')
print(f'获取日志信息中的IP为: {log[0]}与其数量为: {log[1]}')
if net_count>500 and uptime>0.2 and top<85 and diff < 10 and net_recv>200 and get_netstat_ip()==log[0][0]:
print(f'应用服务器当前存在被入侵的风险,风险的IP为:{ip}','日志访问的数量为:',log[1])
deploy_unsafe(ip)
exit('unsafe')