LinuxÇéÐÎϵÄÈÕÖ¾ÆÊÎöÓëÔÆÇå¾²
linuxÇéÐÎϵÄÈÕÖ¾ÆÊÎöÓëÔÆÇå¾²
ÔÆÅÌËãÒѾ³ÉΪÏÖ´úÆóÒµµÄÖ÷Òª×é³É²¿·Ö£¬ÎªÆóÒµÌṩÁËÎÞаÐԺͿÉÀ©Õ¹ÐÔ¡£È»¶ø£¬Ëæ×ÅÔÆÅÌËãµÄÆÕ¼°£¬ÔÆÇå¾²ÎÊÌâÒ²Öð½¥Õ¹ÏÖ¡£¶ñÒâ¹¥»÷¡¢Êý¾Ýй¶ºÍÈëÇÖµÈÇå¾²Íþв¶ÔÆóÒµµÄÔÆÇéÐÎ×é³ÉÁËÖØ´óµÄΣº¦¡£ÎªÁ˸üºÃµØ±£»¤ÔÆÇéÐεÄÇå¾²£¬ÈÕÖ¾ÆÊÎö×÷ΪһÖÖÖ÷ÒªµÄÇå¾²¼à¿ØÊÖ¶Î×îÏÈÊܵ½ÆÕ±é¹Ø×¢¡£
ÔÚLinuxÇéÐÎÏ£¬ÈÕÖ¾ÊǼà¿ØºÍ×·×Ùϵͳ²Ù×÷µÄÖ÷ҪȪԴ¡£Í¨Ì«¹ýÎöÈÕÖ¾£¬¿ÉÒÔ·¢Ã÷Òì³£ÐÐΪ¡¢Ç±ÔÚÍþвºÍÈëÇÖ¼£Ïó¡£Òò´Ë£¬ÕÆÎÕ¸ßЧµÄÈÕÖ¾ÆÊÎöÊÖÒÕ¹ØÓÚ±£»¤ÔÆÇéÐεÄÇå¾²ÖÁ¹ØÖ÷Òª¡£ÏÂÃ潫ÏÈÈÝÔõÑùÔÚLinuxÇéÐÎÖоÙÐÐÈÕÖ¾ÆÊÎö£¬²¢ÍŽá´úÂëʾÀýÀ´ÊµÏÖ»ù±¾µÄÈÕÖ¾ÆÊÎö¹¦Ð§¡£
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÍøÂçϵͳÈÕÖ¾¡£ÔÚLinuxÇéÐÎÏ£¬ÈÕÖ¾Ò»Ñùƽ³£´æ´¢ÔÚ/var/logĿ¼Ï¡£³£¼ûµÄϵͳÈÕÖ¾Îļþ°üÀ¨£º
/var/log/auth.log£º¼ÍÈÎÃü»§ÈÏÖ¤Ïà¹ØÐÅÏ¢¡£
/var/log/syslog£º¼Í¼ϵͳÔËÐÐ״̬ºÍ¹ýʧÐÅÏ¢¡£
/var/log/messages£º¼Í¼ϵͳ¸÷¸ö×é¼þµÄÐÅÏ¢ºÍ¹ýʧ¡£
/var/log/secure£º¼Í¼Çå¾²Ïà¹ØµÄÐÅÏ¢¡£
/var/log/nginx/access.log£º¼Í¼NginxЧÀÍÆ÷»á¼ûÈÕÖ¾¡£
ΪÁËÀû±ãÈÕÖ¾ÆÊÎö£¬ÎÒÃÇ¿ÉÒÔʹÓù¤¾ßÈçsyslog-ng»òrsyslogÀ´¼¯ÖÐÖÎÀíÈÕÖ¾Îļþ¡£
½ÓÏÂÀ´£¬ÎÒÃÇʹÓÃPython±àд´úÂëÀ´ÆÊÎöÈÕÖ¾¡£ÏÂÃæÊÇÒ»¸öʾÀý´úÂ룬ÓÃÓÚͳ¼Æ/var/log/syslogÖи÷¼¶±ðÈÕÖ¾µÄÊýÄ¿£º
import re log_file = '/var/log/syslog' log_level_count = {} with open(log_file, 'r') as f: for line in f: result = re.findall(r'(w+):s', line) if result: log_level = result[0] if log_level in log_level_count: log_level_count[log_level] += 1 else: log_level_count[log_level] = 1 for log_level, count in log_level_count.items(): print(log_level, count)
µÇ¼ºó¸´ÖÆ
ÔËÐÐÉÏÊö´úÂëºó£¬½«Êä³ö²î±ðÈÕÖ¾¼¶±ðµÄÊýÄ¿¡£Í¨Ì«¹ýÎöÈÕÖ¾¼¶±ðµÄÂþÑÜÇéÐΣ¬ÎÒÃÇ¿ÉÒÔ¸üºÃµØÏàʶϵͳµÄÔËÐÐ״̬ºÍÒì³£ÇéÐΡ£
³ýÁËͳ¼ÆÈÕÖ¾ÊýÄ¿£¬ÎÒÃÇ»¹¿ÉÒÔ̫ͨ¹ýÎöÈÕÖ¾ÄÚÈÝÀ´¼ì²âDZÔÚµÄÇå¾²Íþв¡£ÀýÈ磬ÎÒÃÇ¿ÉÒÔ±àд´úÂëÀ´²éÕÒ¾ßÓÐDZÔÚΣº¦µÄÒªº¦×Ö¡£ÏÂÃæÊÇÒ»¸öʾÀý´úÂ룬ÓÃÓÚÔÚ/var/log/auth.logÖвéÕÒ°üÀ¨Òªº¦×Ö”Failed”µÄÐУº
log_file = '/var/log/auth.log' key_word = 'Failed' with open(log_file, 'r') as f: for line in f: if key_word in line: print(line)
µÇ¼ºó¸´ÖÆ
̫ͨ¹ýÎö°üÀ¨”Failed”Òªº¦×ÖµÄÐУ¬ÎÒÃÇ¿ÉÒÔʵʱ·¢Ã÷µÇ¼ʧ°ÜµÄÇéÐΣ¬ÊµÊ±½ÓÄɲ½·¥À´±ÜÃâDZÔÚµÄÈëÇÖ¡£
±ðµÄ£¬ÎÒÃÇ»¹¿ÉÒÔʹÓÃÇ¿Ê¢µÄÈÕÖ¾ÆÊÎö¹¤¾ßÈçELK£¨Elasticsearch, Logstash, Kibana£©À´½øÒ»²½Ìá¸ßÈÕÖ¾ÆÊÎöµÄЧÂʺÍ׼ȷÐÔ¡£ELKÊÇÒ»¸öÊ¢ÐеÄÈÕÖ¾ÆÊÎöƽ̨£¬¾ßÓÐÇ¿Ê¢µÄÊý¾Ý´¦ÀíºÍ¿ÉÊÓ»¯¹¦Ð§¡£Ê¹ÓÃELK£¬ÎÒÃÇ¿ÉÒÔ½«ÈÕÖ¾Êý¾Ýµ¼ÈëElasticsearchÖУ¬È»ºóʹÓÃKibana¾ÙÐÐÊý¾ÝÆÊÎöºÍ¿ÉÊÓ»¯¡£
×ÛÉÏËùÊö£¬LinuxÇéÐÎϵÄÈÕÖ¾ÆÊÎö¹ØÓÚ±£»¤ÔÆÇéÐεÄÇå¾²ÖÁ¹ØÖ÷Òª¡£Í¨¹ýºÏÀíÍøÂç¡¢ÖÎÀíºÍÆÊÎöÈÕÖ¾£¬ÎÒÃÇ¿ÉÒÔ¿ìËÙ·¢Ã÷Ï¢Õù¾öDZÔÚµÄÇå¾²Íþв¡£Ê¹ÓôúÂëʾÀýÍŽáÇ¿Ê¢µÄÈÕÖ¾ÆÊÎö¹¤¾ßÈçELK£¬¿ÉÒÔ½øÒ»²½Ìá¸ßÈÕÖ¾ÆÊÎöµÄЧÂʺÍ׼ȷÐÔ¡£Í¨¹ýһֱѧϰºÍʵ¼ù£¬ÎÒÃÇ¿ÉÒÔ¸üºÃµØÓ¦¶ÔÔÆÇéÐÎÖеÄÇå¾²ÌôÕ½£¬È·±£ÆóÒµµÄÔÆÇå¾²¡£
ÒÔÉϾÍÊÇLinuxÇéÐÎϵÄÈÕÖ¾ÆÊÎöÓëÔÆÇå¾²µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡