#include #include #include #include #include #include #define BUFFER 270 #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" int main(int argc, char *argv[], char **env) { FILE *fp, *fc; char p[2], splice_command[LONG_BUFFER], command[LONG_BUFFER], *temp, buffer[BUFFER], awk[BUFFER], iptables[BUFFER]; time_t timep; struct tm *tp; time(&timep); 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) { return 1; } } else { if ((fp = popen(LE_10, "r")) == NULL) { return 1; } } while (fgets(buffer, BUFFER, fp) != NULL) { temp = strstr(buffer, "rhost"); sscanf(temp, "rhost=%s", temp); 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; } } pclose(fp); pclose(fc); return 0; }