2019-09-24 08:53:00 +08:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <fcntl.h>
|
|
|
|
#include <string.h>
|
|
|
|
#include <time.h>
|
|
|
|
|
|
|
|
#define BUFFER 270
|
2021-07-11 10:10:55 +08:00
|
|
|
#define LONG_BUFFER 1024*100
|
|
|
|
#define TOP_IP 20
|
|
|
|
#define AWK "| awk -v num=%d '{a[$1]+=1;} END {for(i in a){if (a[i] >= num) {print i;}}}' "
|
|
|
|
#define GE_10 "grep -E \"^$(date \"+%h\").$(date \"+%d\")\" /var/log/auth.log | grep failure | grep rhost"
|
|
|
|
#define LE_10 "grep -E \"^$(date \"+%h\")..$(date | awk '{print $3}')\" /var/log/auth.log | grep failure | grep rhost"
|
|
|
|
#define IPTABLES "/sbin/iptables -I INPUT -s %s -j DROP"
|
2019-09-24 08:53:00 +08:00
|
|
|
|
2021-07-11 10:10:55 +08:00
|
|
|
int main(int argc, char *argv[], char **env)
|
2019-09-24 08:53:00 +08:00
|
|
|
{
|
2021-07-11 10:10:55 +08:00
|
|
|
FILE *fp, *fc;
|
|
|
|
char p[2], splice_command[LONG_BUFFER], command[LONG_BUFFER], *temp, buffer[BUFFER], awk[BUFFER], iptables[BUFFER];
|
|
|
|
|
2019-09-24 08:53:00 +08:00
|
|
|
time_t timep;
|
2021-07-11 10:10:55 +08:00
|
|
|
struct tm *tp;
|
2019-09-24 08:53:00 +08:00
|
|
|
time(&timep);
|
2021-07-11 10:10:55 +08:00
|
|
|
tp = localtime(&timep);
|
|
|
|
memset(splice_command, 0, LONG_BUFFER);
|
|
|
|
memset(command, 0, LONG_BUFFER);
|
|
|
|
memset(buffer, 0, BUFFER);
|
|
|
|
memset(awk, 0, BUFFER);
|
|
|
|
memset(iptables, 0, BUFFER);
|
|
|
|
fp = NULL;
|
|
|
|
fc = NULL;
|
|
|
|
|
|
|
|
if (tp->tm_mday >= 10) {
|
|
|
|
if ((fp = popen(GE_10, "r")) == NULL) {
|
2019-09-24 08:53:00 +08:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
} else {
|
2021-07-11 10:10:55 +08:00
|
|
|
if ((fp = popen(LE_10, "r")) == NULL) {
|
2019-09-24 08:53:00 +08:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
}
|
2021-07-11 10:10:55 +08:00
|
|
|
|
2019-09-24 08:53:00 +08:00
|
|
|
while (fgets(buffer, BUFFER, fp) != NULL) {
|
|
|
|
temp = strstr(buffer, "rhost");
|
|
|
|
sscanf(temp, "rhost=%s", temp);
|
2021-07-11 10:10:55 +08:00
|
|
|
if (atoi(strncpy(p, temp, 1)) > 0) {
|
|
|
|
strcat(splice_command, temp);
|
|
|
|
strcat(splice_command, "\n");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
printf("%s", splice_command); // 测试没问题
|
|
|
|
|
|
|
|
// 拼接命令
|
|
|
|
sprintf(awk, AWK, TOP_IP);
|
|
|
|
strcpy(command, "echo \"");
|
|
|
|
strcat(command, splice_command);
|
|
|
|
strcat(command, "\"");
|
|
|
|
strcat(command, awk);
|
|
|
|
//printf("%s", command); // 测试没问题
|
|
|
|
if ((fp = popen(command, "r")) == NULL) { // 执行命令
|
|
|
|
perror("popen");
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
while (fgets(buffer, BUFFER, fp) != NULL) {
|
|
|
|
buffer[strlen(buffer) - 1] = '\0'; // 去除回车
|
|
|
|
sprintf(iptables, IPTABLES, buffer);
|
|
|
|
if ((fc = popen(iptables, "r")) == NULL) {
|
|
|
|
perror("popen");
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2019-09-24 08:53:00 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
pclose(fp);
|
2021-07-11 10:10:55 +08:00
|
|
|
pclose(fc);
|
|
|
|
|
|
|
|
|
2019-09-24 08:53:00 +08:00
|
|
|
return 0;
|
|
|
|
}
|