Computer/PHP

fail2ban 설치하려다 귀찮아서 php 쉘 스크립트 하나 맹금.

알찬돌삐 2018. 6. 21. 18:22

<?php

$exec_string = shell_exec('cat /var/log/secure  | grep "sshd.*failures.*rhost" | awk \'{print $16}\' | awk -F = \'{print $2}\' | uniq -c | sort -n');

$data = explode("\n", $exec_string);

$ip_lists = $output = array();

foreach ($data as $val) {

$row = explode(" ", trim($val));

$row[0] = intval(trim($row[0]));

$row[1] = trim($row[1]);

if ($row[0] > 5) { // 5번 넘게 접속 실패했다면.

$ip_lists[] = $row[1];

}

}


$fp = file('/etc/hosts.deny');

foreach ($fp as $key=>$val) {

if (strpos($val, 'sshd:') === 0) {

$str = trim(str_replace('sshd: ', '', $val));

$tmp = explode(',', $str);

foreach ($tmp as $val2) $ip_lists[] = trim($val2);

$ip_lists = array_unique($ip_lists);

$fp[$key] = 'sshd: '. implode(',', $ip_lists);

}

}


$output = implode("", $fp)."\n";


$fp = fopen('/etc/hosts.deny', 'w');

fwrite($fp, $output);

fclose($fp);

?>




크론에 등록함 끗.