利用Python实时读取fast.log,对级别 <=2 级的预警进行主动响应,调用iptables封禁ip
时间: 2023-12-03 22:47:18 浏览: 33
可以使用Python的 `tail` 模块来实时读取日志文件,然后使用正则表达式匹配日志信息中的级别和IP信息,如果级别小于等于2,则调用 `iptables` 命令封禁该IP。
以下是示例代码:
```python
import re
import subprocess
from tail import Tail
# 定义日志文件路径
log_file = '/var/log/fast.log'
# 创建 Tail 类实例,实现实时读取日志文件
tail = Tail(log_file)
tail.register_callback(process_log)
# 定义正则表达式,匹配日志信息中的级别和IP地址
pattern = r'\[(\d+)\] \[.*?\] \[.*?\] \[.*?\] \[.*?\] \[.*?\] \[.*?\] \[.*?\] (\d+\.\d+\.\d+\.\d+)'
# 定义封禁 IP 的函数
def block_ip(ip):
subprocess.run(f'iptables -I INPUT -s {ip} -j DROP', shell=True)
# 处理日志文件中的每一行日志信息
def process_log(line):
# 使用正则表达式匹配日志信息中的级别和IP地址
match = re.search(pattern, line)
if match:
level = int(match.group(1))
ip = match.group(2)
# 如果级别小于等于2,则封禁该IP
if level <= 2:
block_ip(ip)
# 启动 Tail 类实例,开始实时读取日志文件
tail.follow()
```
需要注意的是,上述代码中调用 `iptables` 命令需要使用 root 权限,因此需要确保 Python 运行的用户具有足够的权限。另外,这种方式只是一个简单的示例,实际应用中还需要考虑一些其他的因素,例如防止误封、防止恶意攻击等。