在网络安全领域,我们经常需要监控服务器的访问日志,并根据IP地址出现的频率来判断是否存在恶意访问。本文将介绍如何使用PHP编写一个脚本,自动统计日志文件中IP出现的次数,并根据设定的阈值自动添加iptables规则来阻止恶意IP的访问。
步骤:
1、首先,我们需要编写一个PHP函数来统计日志文件中IP出现的次数。函数的代码如下:
function countIPOccurrences($logFile) {
$ipCounts = array();
$handle = fopen($logFile, 'r');
if ($handle) {
while (($line = fgets($handle)) !== false) {
preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $line, $matches);
if (!empty($matches)) {
$ip = $matches[0];
if (array_key_exists($ip, $ipCounts)) {
$ipCounts[$ip]++;
} else {
$ipCounts[$ip] = 1;
}
}
}
fclose($handle);
}
return $ipCounts;
}
里面具体正则根据你的log文件的情况来