LinuxÏÂÈÕÖ¾ÖÎÀíÓëÆÊÎöµÄЧÒæºÍÌôÕ½
linuxÏÂÈÕÖ¾ÖÎÀíÓëÆÊÎöµÄЧÒæºÍÌôÕ½
СÐò£º
ÔÚÏÖ´úÊÖÒÕÉú³¤ÈÕÐÂÔÂÒìµÄITÁìÓòÖУ¬ÈÕÖ¾ÖÎÀíÓëÆÊÎöÒѳÉΪÅÌËã»úϵͳÖÎÀíºÍÇå¾²ÐÔµÄÖ÷Òª×é³É²¿·Ö¡£ÓÈÆäÊÇÔÚLinux²Ù×÷ϵͳÖУ¬ÈÕÖ¾ÊǼà¿ØºÍÆÊÎöϵͳÔËÐÐÇéÐεÄÖ÷ÒªÖ¸±ê£¬Ëü¿ÉÒÔ×ÊÖúÎÒÃÇÃ÷ȷϵͳ±¬·¢µÄÊÂÎñÒÔ¼°É¨³ýÎÊÌâ¡£±¾ÎĽ«Ì½ÌÖLinuxÏÂÈÕÖ¾ÖÎÀíÓëÆÊÎöµÄЧÒæÒÔ¼°Ïà¹ØµÄÌôÕ½£¬²¢¸½ÓдúÂëʾÀý¡£
ÈÕÖ¾ÖÎÀíµÄЧÒ棺
1.1 ϵͳ¼à¿ØÓë¹ÊÕÏɨ³ý£º
ÈÕÖ¾¼Í¼²Ù×÷ϵͳ¡¢Ó¦ÓóÌÐòºÍЧÀ͵ÄÔ˶¯£¬¿ÉÒÔ×ÊÖúÖÎÀíÔ±¼à²âϵͳÐÔÄܺÍ״̬¡£µ±ÏµÍ³·ºÆð¹ÊÕÏ»òÒ쳣ʱ£¬ÖÎÀíÔ±¿ÉÒÔ̫ͨ¹ýÎöÈÕÖ¾À´×·×ٺͶ¨Î»ÎÊÌâȪԴ¡£ÀýÈ磬ͨ¹ýÉó²é/var/log/messagesÎļþ£¬¿ÉÒÔÏàʶϵͳÆô¶¯¡¢¹Ø»ú¡¢Ð§ÀÍÆôÍ£µÈÒªº¦ÊÂÎñ£¬×ÊÖú¿ìËÙÆÊÎöϵͳÐÔÄÜÎÊÌâ¡£
1.2 Çå¾²Éó¼ÆÓëÍþв¼ì²â£º
ÈÕÖ¾¼Í¼»¹¿ÉÒÔÓÃÓÚϵͳÇå¾²Éó¼ÆºÍÍþв¼ì²â¡£Í¨¹ý¼à¿ØϵͳÈÕÖ¾£¬ÖÎÀíÔ±¿ÉÒÔ¼ì²éδ¾ÊÚȨµÄ»á¼û¡¢Òì³£ÐÐΪºÍÇå¾²ÊÂÎñ¡£ÀýÈ磬ͨ¹ýÉó²é/var/log/auth.logÎļþ£¬¿ÉÒÔ×·×Ùµ½Óû§µÇ¼ÐÅÏ¢¡¢ÏµÍ³ÊÚȨÐÐΪµÈ£¬×ÊÖúÖÎÀíԱʵʱ·¢Ã÷²¢Ó¦¶ÔÇå¾²Íþв¡£
1.3 ÐÔÄÜÓÅ»¯£º
̫ͨ¹ýÎöϵͳÈÕÖ¾£¬¿ÉÒÔ·¢Ã÷ϵͳµÄÆ¿¾±ºÍÐÔÄÜÎÊÌâ¡£ÀýÈ磬Éó²é/var/log/nginx/access.logÎļþ¿ÉÒÔÏàʶµ½NginxЧÀ͵Ļá¼ûÇéÐΣ¬×ÊÖúÓÅ»¯Ð§À͵ÄÏìÓ¦ËÙÂʺÍÍÌÍÂÁ¿¡£
ÈÕÖ¾ÖÎÀíµÄÌôÕ½£º
2.1 ÈÕÖ¾Á¿¹ý´ó£º
ÏÖ´úϵͳÌìÉúµÄÈÕÖ¾Á¿Öش󣬻á¸øÈÕÖ¾ÖÎÀíºÍÆÊÎö´øÀ´ÌôÕ½¡£´ó×ÚµÄÈÕÖ¾Êý¾ÝÐèÒªÍøÂç¡¢´æ´¢ºÍ´¦Öóͷ££¬ÐèҪ˼Á¿´æ´¢¿Õ¼äºÍÅÌËã×ÊÔ´µÄÐèÇó¡£
2.2 ÈÕÖ¾ÃûÌúͽṹ·×ÆçÖ£º
²î±ðÓ¦ÓóÌÐòºÍЧÀÍÌìÉúµÄÈÕÖ¾ÃûÌúͽṹ¿ÉÄÜ·×ÆçÖ£¬µ¼ÖÂÈÕÖ¾ÖÎÀíºÍÆÊÎöµÄÖØ´óÐÔÔöÌí¡£ÀýÈ磬ApacheºÍNginxµÈWebЧÀÍÆ÷µÄÈÕÖ¾ÃûÌÿÉÄܲî±ð£¬µ¼ÖÂÆÊÎö¹¤¾ßÐèÒª¾ÙÐÐÊÊÅäÏ¢ÕùÎö¡£
2.3 ʵʱÐÔÒªÇó£º
ϵͳÈÕÖ¾¿ÉÄÜÐèҪʵʱ¼à²âºÍÆÊÎö£¬Õâ¶ÔÈÕÖ¾ÖÎÀí¹¤¾ßºÍϵͳµÄÐÔÄÜÌá³öÁ˸ü¸ßÒªÇó¡£µ±ÐèҪʵʱ¼ì²âºÍÏìӦϵͳ¹ÊÕÏ»òÇå¾²Íþвʱ£¬ÖÎÀíÔ±ÐèҪѡÔñºÏÊʵÄÈÕÖ¾ÖÎÀí¹¤¾ßºÍ¼Ü¹¹¡£
´úÂëʾÀý£º
ÒÔÏÂÊÇÒ»¸ö¼òÆÓµÄPython¾ç±¾Ê¾Àý£¬ÓÃÓÚÆÊÎöNginx»á¼ûÈÕÖ¾ÎļþÖеÄÇëÇóÁ¿ºÍÇëÇóIP£º
import re log_file = '/var/log/nginx/access.log' def count_requests(): request_count = 0 ip_set = set() with open(log_file, 'r') as f: lines = f.readlines() for line in lines: match = re.search(r'(d+.d+.d+.d+)s', line) if match: ip = match.group(1) ip_set.add(ip) request_count += 1 return request_count, len(ip_set) if __name__ == '__main__': total_requests, unique_ips = count_requests() print("Total requests:", total_requests) print("Unique IPs:", unique_ips)
µÇ¼ºó¸´ÖÆ
¸Ã¾ç±¾»á¶ÁÈ¡NginxµÄ»á¼ûÈÕÖ¾Îļþ£¬²¢Í³¼Æ×ÜÇëÇóÊýºÍ×ÔÁ¦IPÊý¡£Í¨¹ýÔËÐÐÕâ¸ö¾ç±¾£¬¿ÉÒÔ¿ìËÙÏàʶÍøÕ¾µÄ»á¼ûÇéÐΡ£
½áÂÛ£º
ÈÕÖ¾ÖÎÀíÓëÆÊÎöÔÚLinuxϵͳÖоßÓÐÖ÷ÒªÒâÒ壬¿ÉÒÔ×ÊÖúÖÎÀíÔ±¼à¿Ø¡¢É¨³ý¹ÊÕÏ¡¢ÌáÉýϵͳÐÔÄÜ£¬²¢ÌṩÇå¾²Éó¼ÆºÍÍþв¼ì²âµÄ¹¦Ð§¡£È»¶ø£¬ÃæÁÙÈÕÒæÔöÌíµÄÈÕÖ¾Êý¾ÝºÍ·×ÆçÖµÄÈÕÖ¾ÃûÌã¬ÎÒÃÇÐèҪѡÓúÏÊʵŤ¾ßºÍÊÖÒÕÀ´½â¾öÈÕÖ¾ÖÎÀíÓëÆÊÎöµÄÌôÕ½£¬ÎªÏµÍ³Î¬»¤ºÍÇå¾²Ìṩ֧³Ö¡£
²Î¿¼×ÊÁÏ£º
https://www.infoq.com/articles/linux-log-files/
https://www.linuxjournal.com/content/effective-log-file-management
ÒÔÉϾÍÊÇLinuxÏÂÈÕÖ¾ÖÎÀíÓëÆÊÎöµÄЧÒæºÍÌôÕ½µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡