본문 바로가기

공부/리눅스

로그서비스 - syslog / logrotate / logwatch

반응형
로그서비스(syslog)

로그파일 종류

/var/log 디렉토리에 위치
- messages : 시스템 운영에 대한 전반적인 기록
- boot.log : 부팅될때 출력되는 메시지 기록
cron : cron log
secure : 원격접속기록
xferlog : ftp 서비스의 파일 송수신 기록
wtmp : 사용자 접속기록
lastlog : 각 계정의 가장 최근 로그인 시간 기록
          (로그인시 이정보가 자동 출력된다)

syslog.conf

모든 룰은 두개의 필드, 셀렉터 필드와 액션 필드로 구성된다.
그리고 이 두개의 필드는 한개이상의 스페이스 문자 또는 탭문자로 구분되어진다.


설정문법
selecter 한개이상의 스페이스 또는 탭문자 action
selector 는 facility.priority 로 구성된다.

facility 및 priority (또는 level 이라고도 한다)
/usr/include/sys/syslog.h 에 정의되어 있다.

 * priorities (these are ordered)
 */
#define LOG_EMERG      0      /* system is unusable */
#define LOG_ALERT      1      /* action must be taken immediately */
#define LOG_CRIT        2      /* critical conditions */
#define LOG_ERR        3      /* error conditions */
#define LOG_WARNING    4      /* warning conditions */
#define LOG_NOTICE      5      /* normal but significant condition */
#define LOG_INFO        6      /* informational */
#define LOG_DEBUG      7      /* debug-level messages */


/* facility codes */
#define LOG_KERN        (0<<3)  /* kernel messages */
#define LOG_USER        (1<<3)  /* random user-level messages */
#define LOG_MAIL        (2<<3)  /* mail system */
#define LOG_DAEMON      (3<<3)  /* system daemons */
#define LOG_AUTH        (4<<3)  /* security/authorization messages */
#define LOG_SYSLOG      (5<<3)  /* messages generated internally by syslogd */
#define LOG_LPR        (6<<3)  /* line printer subsystem */
#define LOG_NEWS        (7<<3)  /* network news subsystem */
#define LOG_UUCP        (8<<3)  /* UUCP subsystem */
#define LOG_CRON        (9<<3)  /* clock daemon */
#define LOG_AUTHPRIV    (10<<3) /* security/authorization messages (private) */
#define LOG_FTP        (11<<3) /* ftp daemon */

        /* other codes through 15 reserved for system use */
#define LOG_LOCAL0      (16<<3) /* reserved for local use */
#define LOG_LOCAL1      (17<<3) /* reserved for local use */
#define LOG_LOCAL2      (18<<3) /* reserved for local use */
#define LOG_LOCAL3      (19<<3) /* reserved for local use */
#define LOG_LOCAL4      (20<<3) /* reserved for local use */
#define LOG_LOCAL5      (21<<3) /* reserved for local use */
#define LOG_LOCAL6      (22<<3) /* reserved for local use */
#define LOG_LOCAL7      (23<<3) /* reserved for local use */

*. auth 와 authpriv는 비슷하지만 조금 차이가 있다.
auth는 원격서비스 접속기록을 남기며
authpriv 는 su 명령어 사용기록, 로그인 성공 및 실패여부의 기록을 남긴다.

*. facility LOCAL0 ~ LOCAL7은 booting 기록이나 기타 여분의 용도로 사용한다.

syslog.conf 파일에서 facility 를 지정할때는 위에 정의된 LOG_KERN 인경우
kern 으로 설정한다. priority 도 마찬가지로 소문자로 crit 이런식으로 표기한다.
예) kern.crit;user.err

로그 설정에 대한 몇가지 예
kern.*          /var/adm/kernel 
=> 커널로부터 발생된 모든 레벨의 메세지를 오른쪽의 파일에 기록
kern.crit      @unix1
=>  커널로부터 발생된 메세지중 crit 이상의 레벨 메세지를 unix1 호스트로  포워딩.
kern.crit      /dev/console
=> 커널로부터 발생된 메세지중 crit 이상의 레벨 메세지를 console(tty1,tty2...) 에 보냄
kern.info;kern.!err      /var/adm/kernel-info
=> 커널로부터 발생된 메세지중 info 레벨부터 err 레벨 바로 아래까지의 레벨메세지를
kernel-info 파일에 기록
*.info    /var/log/messages
=>  info 레벨 이상의 모든 facility 의 메세지를 오른쪽 파일에 기록
*.* /var/log/messages
=> 모든 selector 의 메세지를 /var/log/messages 파일에 기록
user.info  user1,user2
=> 사용자 프로세스로부터 발생된 메세지중 info 레벨 이상의 메세지를  user1과 user2
사용자에게 보냄
mail.* *
=>  mail 서비스로부터 발생된 메세지를 접속해 있는 모든사용자에게 보냄.

*. 기타 자세한 설정 방법은 syslog.conf 의 메뉴얼 페이지 참조.

로그서비스 테스트

로그서비스를 가장 간단히 시험할수 있는 툴로 logger 가 있다.

간단한 사용법은 아래와 같다.
logger [ -p selector ] message
ex) logger -p daemon.notice "daemon log test ....."

* Remote log

원격지에서 보내지는 로그를 받기위해서는

/etc/sysconfig/syslog

=> SYSLOGD_OPTIONS="-m 0"  =>  SYSLOGD_OPTIONS="-m 0 -r" 로 수정한다.

/etc/syslog.conf에는

*.* @host이름


logrotate -  rotates, compresses, and mails system logs

로그파일을 적절하게 관리하지 않으면 계속 쌓여서 너무 커질 수 있으며
그것으로 인하여 디스크가 Full 이 될수 있다.
또한 로그파일이 커질수록 syslog 데몬이 로그파일에 메세지를 남기는데
더 많은 부하를 초래하게 된다.
그러므로 로그파일이 너무 커지지 않게 관리해주어야 하는데 이때 필요한것이
logrotate 이다.
logrotate 는 로그파일을 주기적으로 백업시켜주고, 압축, 삭제, 메일로 전송등의
작업을 할 수 있다.

확인해보고 설치 안되어 있으면 yum 으로 설치한다.
[root@centos1 ~]# rpm -q logrotate
logrotate-3.7.4-9
[root@centos1 ~]#

[root@centos1 ~]# rpm -ql logrotate
/etc/cron.daily/logrotate
/etc/logrotate.conf
/etc/logrotate.d
/usr/sbin/logrotate
/usr/share/doc/logrotate-3.7.4
/usr/share/doc/logrotate-3.7.4/CHANGES
/usr/share/man/man8/logrotate.8.gz
/var/lib/logrotate.status
[root@centos1 ~]#

logrotate 를 설치하게 되면 자동으로 crontab 에 등록된다.

root@centos1 etc]# ls /etc/cron.daily/logrotate
/etc/cron.daily/logrotate
[root@centos1 etc]#

[root@centos1 etc]# grep cron.daily /etc/crontab
02 4 * * * root run-parts /etc/cron.daily
[root@centos1 etc]#
*. 위에처처럼 확인할 수 있다.

rogloate.conf 파일 - 아래처럼 되어 있다.

  1 # see "man logrotate" for details
  2 # rotate log files weekly
  3 weekly
  4
  5 # keep 4 weeks worth of backlogs ; 백업된 로그파일을 4주간 남겨둠
              (한주에 한개씩 rotate)
  6 rotate 4
  7
  8 # create new (empty) log files after rotating old ones ; 오래된 파일을 rotate(순환)시킨후
  새로운 빈 로그파일을 만든다.
  9 create
 10
 11 # uncomment this if you want your log files compressed
 12 #compress  < = 로그파일을 압축하려면 주석을 풀어주면 된다.
 13
 14 # RPM packages drop log rotation information into this directory
 15 include /etc/logrotate.d  <= 이 디렉토리의 모든 파일을 여기에 포함하라는 의미.
 16
 17 # no packages own wtmp -- we'll rotate them here
 18 /var/log/wtmp {
 19    monthly
 20    minsize 1M
 21    create 0664 root utmp
 22    rotate 1
 23 }
 24

[root@centos1 logrotate.d]# cat /etc/logrotate.d/vsftpd.log
/var/log/vsftpd.log {
    # ftpd doesn't handle SIGHUP properly
    nocompress      <= 로그파일을 압축하지 않는다.
    missingok <= 로그파일(vsftpd.log)이 없어도 에러를 발생시키지 않는다.
(nomissingok 는 반대되는 의미이며 생략했을때 디폴트값)
}

[root@centos1 logrotate.d]#

[root@centos1 logrotate.d]# cat /etc/logrotate.d/samba
/var/log/samba/*.log {
    notifempty
    missingok
    sharedscripts
    copytruncate
    postrotate
        /bin/kill -HUP `cat /var/run/smbd.pid /var/run/nmbd.pid /var/run/winbindd.pid 2> /dev/null` 2> /dev/null || true 
    endscript
}
[root@centos1 logrotate.d]#

notifempty : 로그파일이 비어 있을경우에는 rotate 하지 않는다.
디폴트는 ifempty이며 로그파일이 비어 있을경우에도 rotate 한다.
missingok : 로그파일이 없어도 에러를 발생시키지 않는다.
디폴트는 nomissingok 이며 로그파일이 없는 경우 에러를 발생시킨다.
sharedscripts : 로그파일이 rotate 될때 단 한번 prerotate 와 postrotate 가 실행된다.               
nosharedscipts : 로그파일이 rotate 될때마다 prerotate와 postrotate 를 실행한다.
postrotate / endscript : rotate 한후의작업.
prerotate / endscript : rotate 하기전의 작업
copytruncate : 로그파일의 복사본을 만든후 원래의 로그파일 내용을 비우고 거기에 log를 새로 기록한다.
로그를 발생시키는 어떤 프로그램은 log 파일을 계속 열어두어야 하는것도 있다.
/bin/kill -HUP `cat /var/run/smbd.pid /var/run/nmbd.pid /var/run/winbindd.pid 2> /dev/null` 2> /dev/null || true
smbd 데몬과 nmbd 데몬 재시작, 재시작할때 에러가 발생되더라도 모니터로 출력하지 않으며 실행여부에 관계없이
참을 리턴한다.(리턴값은 항상 shell 이 받습니다. 리턴값을 가지고 다른 일을 처리하는경우 유용합니다.)



logwatch
- 로그를 정리해서 지정된 메일주소로 보내준다.(설치할때 크론에 하루 한번 실행되게 등록된다)
[root@centos1 ~]# ls -l /usr/sbin/logwatch
lrwxrwxrwx 1 root root 39  6월 25  2009 /usr/sbin/logwatch -> /usr/share/logwatch/scripts/logwatch.pl
[root@centos1 ~]#
logwatch는 바이너리 파일이 아니라 펄(perl)로 작성된 프로그램이다.

주요옵션
--detail level ( level 은 low, medium, high 또는 0,5,10)
--service servicename (특정서비스의 기록만 출력할 경우)
--print 표준출력으로 출력
--range (yesterday,today,all)
--save file명 (출력을 파일로 저장)
--logdir 디렉토리명 (디폴트 디렉토리대신 사용)

ex) root@server /root# logwatch  --service sshd --detail low --print

 ################### Logwatch 7.3 (03/24/06) ####################
        Processing Initiated: Mon Dec  6 11:20:49 2010
        Date Range Processed: yesterday
                              ( 2010-Dec-05 )
                              Period is day.
      Detail Level of Output: 0
              Type of Output: unformatted
          Logfiles for Host: linux1
  ##################################################################

 --------------------- SSHD Begin ------------------------

 Disconnecting after too many authentication failures for user:
    root : 1 Time(s)

 Failed logins from:
    192.168.197.1: 4 times

 Users logging in through sshd:
    root:
      192.168.197.1: 12 times
      172.20.10.101 (linux101): 1 time
    user1:
      172.20.10.101 (linux101): 1 time
      192.168.197.1: 1 time

 ---------------------- SSHD End -------------------------


 ###################### Logwatch End #########################

 root@server /root#


주요 로그설정파일
기록될 서비스 경로

주요설정항목

LogDir = /var/log
MailTo = root  ; 계정을 적거나 완전한 이메일 주소를 적는다.
MailFrom = logwatch ; 메일로 받았을때 수신자가 logwatch로 표시된다.
Detail = Low ; High 로 설정하면 좀 더 자세한 로그를 볼수 있다.

설치하면 크론에 자동으로 등록된다.

-----------------------------------------------------------------------------------------------------------------------------------------

log service 예제

1.에러 이상의 priority를 갖는 메일  facility를 /var/log/mailerror 파일에 기록되게 설정하시오
2. sysadmin 이라는 사용자를 생성하고 ftp facility 의 모든 priority를 /var/log/ftplog 에 기록되게 설정하고 sysadmin 계정에게도 메세지가 전달되게 하시오.
3. selector 가 local0.err 인 경우 /var/log/local0 파일에 기록되게 설정하고
logger 명령을 테스트하시오.
4. 사용자 인증시 info level 이상의 priority를 /var/log/auth_log 파일에 기록되게 설정하시오
5. selector가 local1.info 인 경우 메시지를 접속해 있는 모든사용자의 콘솔에 뿌려지게 설정하시오.
6. selecto가 local2.notice인 경우 메시지를 /var/log/local2 파일에 기록되게 하고 동시에
192.168.xxx.xxx 의 서버의 /var/log/remote_log 파일에도 저장되게 하시오.
7. 사용자 로그인정보(인증정보)를 remote 서버의 /var/log/secure 파일에도 기록되게
설정하시오

----------------------------------------------------------------------------------------------------------------------------------
logrotate 예제
아래와 같은 조건으로 vsftpd 의 로그를 남기시오

조건.
1. 파일명은 /var/log/vsftpd.log 로 한다.
2. 백업로그파일을 5일간 남겨둔다.
3. rotate 주기는 매일.
4. 5일이 지난 로그파일은 logadmin@localhost 로 메일로 자동전송되게한후 삭제되게한다.
5. 로그파일이 압축되어 저장되게 한다.
6. 로그파일이 rotate 된후 vsftpd 서비스를 자동으로 재시작되게 한다.

----------------------------------------------------------------------------------------------------------------------------------
logwatch 예제

아래 조건에 맞게 logwatch 를 설정하시오

조건.
1. log 출력의 detail level을 medium 으로 하시오.
2. logwatch 관리자에게 매일 새벽 두시에 log를 메일로 전송되게
설정하시오.

반응형