- Today
- Total
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
- deeplearning4j
- presigned
- 숲느낌
- 인계동
- 구 트위터
- secrets manager
- java
- python
- adverising
- mongo to mysql
- Cannot have overlapping
- secrets-manager-config
- 이미지오류
- 주차가능
- Configuration is ambiguously defined. Cannot have overlapping suffixes in two rules if the prefixes are overlapping for the same event type.
- Jakarta Persistence
- Cannot have overlapping suffixes in two rules if the prefixes are overlapping for the same event type.
- Index 1 out of bounds for length 1
- amozon
- AWS
- unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
- opennlp
- 수원
- 몽고디비 클론
- mongodb atlas
- 수원맛집
- source endpoint
- 401error
- 데이트코스
- secrets manager example code
DevOps-Life
rSyslog 적용방법과 history를 이용한 커멘드 로그출력 본문
서버를 이용하다보면 좋던 싫던 로그를 모아두는일이 생긴다.
그럴 때 리눅스에서는 쉽게 사용할 수 있는게 rSyslog 이고, 윈도우 경우에는 Correlog등 여러 툴이 존재한다.
오늘은 리눅스의 rSyslog와 커멘드까지 로그에 출력하도록 설정해보자
(install 부분은 생략하겠습니다. 적용법만.)
첫번째로
/etc/rsyslog.conf (client)
#가장윗줄에 추가한다
*.* @(rsyslog Server IP) ## *.*(스페이스바)@ IP : 띄어쓰기 중요
# provides UDP syslog reception ### 필자는 UDP 514포트를사용
$ModLoad imudp
$UDPServerRun 514
# provides TCP syslog reception ### TCP 사용시 밑 2줄 주석해제 위 2줄 주석처리
#$ModLoad imudp
#$TCPServerRun 514
간단하게는 이 설정이면 끝이나고 로그에대한 옵션을 추가하려면 더 밑에 옵션에서 변경하면 된다.
Server 같은경우는 가장윗줄 아이피를 안적으면 끝.
히스토리를 이용한 커멘드 로그 출력도 간단하다.
찾아내기가 힘들뿐...
/etc/bash_franzi ##(이파일은 생성)
if [ "${SHELL##*/}" != "bash" ]; then
return
fi
#to avoid sourcing this file more than once
if [ -n "${OSTYPE##solaris*}" ]; then #following not working in solaris
#do not source this file twice; also do not source it if we are in forcecommand.sh, source it later from "-bash-li"
#if we would source it from forcecommand.sh, the environment would be lost after the call of 'exec -l bash -li'
if [ "$AUDIT_INCLUDED" == "$$" ] || { [ -z "$SSH_ORIGINAL_COMMAND" ] && [ "$(cat /proc/$$/cmdline)" == 'bash-c"/etc/forcecommand.sh"' ]; }; then
return
else
declare -rx AUDIT_INCLUDED="$$"
fi
fi
#prompt & color
#'http://www.pixelbeat.org/docs/terminal_colours/#256'
#'http://www.frexx.de/xterm-256-notes/'
_backnone="\e[00m"
_backblack="\e[40m"
_backblue="\e[44m"
_frontred_b="\e[01;31m"
_frontgreen_b="\e[01;32m"
_frontgrey_b="\e[01;37m"
_frontgrey="\e[00;37m"
_frontblue_b="\e[01;34m"
#PS1="\[${_backblue}${_frontgrey_b}\]\u@\h:\[${_backblack}${_frontblue_b}\]\w\\$\[${_backnone}${_frontgrey_b}\] " #grey
PS1="\[${_backblue}${_frontgreen_b}\]\u@\h:\[${_backblack}${_frontblue_b}\]\w\\$\[${_backnone}${_frontgreen_b}\] " #green
#PS1="\[${_backblue}${_frontred_b}\]\u@\h:\[${_backblack}${_frontblue_b}\]\w\\$\[${_backnone}${_frontred_b}\] " #red
declare -rx PS1
#'history' options
declare -rx HISTFILE="$HOME/.bash_history"
declare -rx HISTSIZE=500000 #nbr of cmds in memory
declare -rx HISTFILESIZE=500000 #nbr of cmds on file
declare -rx HISTCONTROL="" #does not ignore spaces or duplicates
declare -rx HISTIGNORE="" #does not ignore patterns
declare -rx HISTCMD #history line number
#following line is commented to avoid following issue: loading the history during the sourcing of this file (non-interactive bash) is also loading history lines that begin with '#', but then during the trap DEBUG calls it reloads the whole history without '#'-lines and produces an double-length history.
#history -r #to reload history from file if a prior HISTSIZE has truncated it
#following 2 lines commented because 'history -r' was still loading '#'-lines
#shopt -s extglob #enable extended pattern matching operators
#HISTIGNORE="*([ \t])#*"; history -r #reload history without commented lines; this force non-interactive bash to behave like interactive bash, without this AUDIT_HISTLINE will get a wrong initial value, leading then to a small issue where empty bash sessions are actually logging the last command of history
if [ -n "${OSTYPE##solaris*}" ]; then #following not working in solaris
if groups | grep -q root; then
declare -x TMOUT=43200 #timeout for root's sessions
chattr +a "$HISTFILE" #set append-only
fi
fi
shopt -s histappend
shopt -s cmdhist
#history substitution ask for a confirmation
shopt -s histverify
#add timestamps in history - obsoleted with logger/syslog
#'http://www.thegeekstuff.com/2008/08/15-examples-to-master-linux-command-line-history/#more-130'
#declare -rx HISTTIMEFORMAT='%F %T '
#enable forward search ('ctrl-s')
#'http://ruslanspivak.com/2010/11/25/bash-history-incremental-search-forward/'
if shopt -q login_shell && [ -t 0 ]; then
stty -ixon
fi
#bash audit & traceability
#
#
#
declare -rx AUDIT_LOGINUSER="$(who -mu | awk '{print $1}')"
declare -rx AUDIT_LOGINPID="$(who -mu | awk '{print $6}')"
declare -rx AUDIT_USER="$USER" #defined by pam during su/sudo
declare -rx AUDIT_PID="$$"
declare -rx AUDIT_TTY="$(who -mu | awk '{print $2}')"
declare -rx AUDIT_SSH="$([ -n "$SSH_CONNECTION" ] && echo "$SSH_CONNECTION" | awk '{print $1":"$2"->"$3":"$4}')"
declare -rx AUDIT_STR="[audit $AUDIT_LOGINUSER/$AUDIT_LOGINPID as $AUDIT_USER/$AUDIT_PID on $AUDIT_TTY/$AUDIT_SSH]"
declare -x AUDIT_LASTHISTLINE="" #to avoid logging the same line twice
declare -rx AUDIT_SYSLOG="1" #to use a local syslogd
#
#
#
#the logging at each execution of command is performed with a trap DEBUG function
#and having set the required history options (HISTCONTROL, HISTIGNORE)
#and to disable the trap in functions, command substitutions or subshells.
#it turns out that this solution is simple and works well with piped commands, subshells, aborted commands with 'ctrl-c', etc..
set +o functrace #disable trap DEBUG inherited in functions, command substitutions or subshells, normally the default setting already
shopt -s extglob #enable extended pattern matching operators
function AUDIT_DEBUG() {
if [ -z "$AUDIT_LASTHISTLINE" ]; then #initialization
local AUDIT_CMD="$(fc -l -1 -1)" #previous history command
AUDIT_LASTHISTLINE="${AUDIT_CMD%%+([^ 0-9])*}"
else
AUDIT_LASTHISTLINE="$AUDIT_HISTLINE"
fi
local AUDIT_CMD="$(history 1)" #current history command
AUDIT_HISTLINE="${AUDIT_CMD%%+([^ 0-9])*}"
if [ "${AUDIT_HISTLINE:-0}" -ne "${AUDIT_LASTHISTLINE:-0}" ] || [ "${AUDIT_HISTLINE:-0}" -eq "1" ]; then #avoid logging unexecuted commands after 'ctrl-c', 'empty+enter', or after 'ctrl-d'
echo -ne "${_backnone}${_frontgrey}" #disable prompt colors for the command's output
#remove in last history cmd its line number (if any) and send to syslog
if [ -n "$AUDIT_SYSLOG" ]; then
if ! logger -p user.info -t "$AUDIT_STR $PWD" "${AUDIT_CMD##*( )?(+([0-9])?(\*)+( ))}"; then
echo error "$AUDIT_STR $PWD" "${AUDIT_CMD##*( )?(+([0-9])?(\*)+( ))}"
fi
else
echo $( date +%F_%H:%M:%S ) "$AUDIT_STR $PWD" "${AUDIT_CMD##*( )?(+([0-9])?(\*)+( ))}" >>/var/log/userlog.info
fi
#echo "===cmd:$BASH_COMMAND/subshell:$BASH_SUBSHELL/fc:$(fc -l -1)/history:$(history 1)/histline:${AUDIT_CMD%%+([^ 0-9])*}/last_histline:${AUDIT_LASTHISTLINE}===" #for debugging
return 0
else
return 1
fi
}
#
#
#
#audit the session closing
function AUDIT_EXIT() {
local AUDIT_STATUS="$?"
if [ -n "$AUDIT_SYSLOG" ]; then
logger -p user.info -t "$AUDIT_STR" "#=== session closed ==="
else
echo $( date +%F_%H:%M:%S ) "$AUDIT_STR" "#=== session closed ===" >>/var/log/userlog.info
fi
exit "$AUDIT_STATUS"
}
#
#
#
#make audit trap functions readonly; disable trap DEBUG inherited (normally the default setting already)
declare -frx +t AUDIT_DEBUG
declare -frx +t AUDIT_EXIT
#
#
#
#audit the session opening
if [ -n "$AUDIT_SYSLOG" ]; then
logger -p user.info -t "$AUDIT_STR" "#=== session opened ===" #audit the session openning
else
echo $( date +%F_%H:%M:%S ) "$AUDIT_STR" "#=== session opened ===" >>/var/log/userlog.info
fi
#
#
#
#when a bash command is executed it launches first the AUDIT_DEBUG(),
#then the trap DEBUG is disabled to avoid a useless rerun of AUDIT_DEBUG() during the execution of pipes-commands;
#at the end, when the prompt is displayed, re-enable the trap DEBUG
#declare -rx PROMPT_COMMAND="AUDIT_DONE=; trap 'AUDIT_DEBUG && AUDIT_DONE=1; trap DEBUG' DEBUG; [ -n \"\$AUDIT_DONE\" ] && echo '-----------------------------'"
#NOK: declare -rx PROMPT_COMMAND="echo "-----------------------------"; trap 'AUDIT_DEBUG; trap DEBUG' DEBUG; echo '-----------------------------'"
#OK: declare -rx PROMPT_COMMAND="echo "-----------------------------"; trap 'AUDIT_DEBUG; trap DEBUG' DEBUG"
declare -rx PROMPT_COMMAND="[ -n \"\$AUDIT_DONE\" ] && echo '-----------------------------'; AUDIT_DONE=; trap 'AUDIT_DEBUG && AUDIT_DONE=1; trap DEBUG' DEBUG"
declare -rx BASH_COMMAND #current command executed by user or a trap
declare -rx SHELLOPT #shell options, like functrace
trap AUDIT_EXIT EXIT #audit the session closing
#endof
이 설정을 담은 파일을 생성해 준 후
퍼미션을 바꿔준다.
# chown root:root /etc/bash_franzi
# chmod 644 /etc/bash_franzi
또한 커멘드에
# for i in /etc/profile /etc/skel/.bashrc /root/.bashrc /home/*/.bashrc; do
if ! grep -q ". /etc/bash_franzi" "$i"; then
echo "===updating $i==="
echo "[ -f /etc/bash_franzi ] && . /etc/bash_franzi #added by francois scheurer" >>"$i"
fi
done
를 넣어주면 끝.
그렇게 되면 /var/log/messages 에 입력하는 커멘드가 찍히는 것을 확인할 수 있다.
오늘의 간단한 꿀팁 여기까지.
'IT > System' 카테고리의 다른 글
[AWS DMS] MongoDB Atlas To AWS RDS(Mysql) endpoint 생성 (0) | 2023.11.07 |
---|---|
[AWS] Configuration is ambiguously defined. Cannot have overlapping suffixes in two rules if the prefixes are overlapping for the same event type. (1) | 2023.09.14 |
SSH 공개키와 개인키 (0) | 2018.12.31 |
SSH등 접근제어 hosts.allow, hosts.deny (0) | 2018.11.20 |
Docker network IP 변경 (기존 네트워크 변경) (2) | 2018.11.19 |