Amazon EC2에서 입력한 명령어를 로그로 출력해 봤습니다.

Amazon EC2에서 입력한 명령어를 로그로 출력해 봤습니다.

Amazon EC2에서 입력한 명령어를 로그로 출력해 봤습니다.
Clock Icon2025.02.19

안녕하세요 클래스메소드 김재욱(Kim Jaewook) 입니다. 이번에는 Amazon EC2에서 입력한 명령어를 로그로 출력해 봤습니다.

EC2 Linux에서 입력한 명령어 출력

EC2 Linux에서 입력한 명령어를 출력하는 방법은 간단합니다.

[sh-5.2$]# sudo -i
[root@ip-xx-x-xx-xxx ~]# cat /root/.bash_history

기본적으로 입력한 명령어는 [.bash_history]에 저장되기 때문에 해당 파일을 통해 입력한 명령어를 확인할 수 있습니다.

cat을 통해서도 출력할 수 있지만 다음 명령을 통해서도 출력할 수 있습니다.

[root@ip-xx-x-xx-xxx ~]# history
    1  yum update -y
    2  cat ~/.bash_history
    3  cat /home/ec2-user/.bash_history
    4  cat ~/.sh_history
    5  echo $HISTFILE
    6  cat /root/.bash_history
    7  shopt histappend
    8  shopt -s histappend
    9  cat /root/.bash_history
   10  echo $HISTSIZE
   11  echo $HISTFILESIZE
   12  exit
   13  echo $HISTFILE /root/.bash_history
   14  ca /root
   15  ls
   16  cd root
   17  cat /root/.bash_history
   18  history

간단하게 [history]를 입력해서 입력한 명령어를 출력할 수 있습니다.

No such file or directory 문제

EC2 인스턴스에서 명령어 로그를 입력했더니 다음과 같이 에러 메시지가 출력되었습니다.

[root@ip-xx-x-xx-xxx ~]# cat /root/.bash_history
cat: /root/.bash_history: No such file or directory

파일 혹은 디렉터리를 찾을 수 없다는 에러 메시지가 출력되었습니다.

[root@ip-xx-x-xx-xxx ~]# echo $HISTFILE
/root/.bash_history

다음 명령어를 통해 Bash의 히스토리 기록 기능이 활성화 되어 있는지 확인합니다. [/root/.bash_history]와 같이 결과 값이 출력됐다면 기능이 활성화 되어 있는 것이고, 아무것도 출력이 되지 않았다면 비활성화된 상태입니다.

[root@ip-xx-x-xx-xxx ~]# shopt histappend
histappend      on

또한, [shopt histappend] 명령어로 현재 히스토리 기록 기능의 on,off 상태를 확인할 수 있는데, on이라고 출력된다면 기록 기능이 활성화된 상태입니다.

[root@ip-xx-x-xx-xxx ~]# shopt -s histappend
[root@ip-xx-x-xx-xxx ~]# exit

활성화 되지 않았다면 상기 명령어를 통해 활성화시키고, 세션을 종료하면 히스토리가 자동으로 저장됩니다. 이어서 다시 확인해 보면, 성공적으로 입력한 명령어 로그를 확인할 수 있습니다.

이렇게 확인한 로그를 S3 버킷에 옮겨 별도로 관리할 수도 있습니다. 이러한 방법은 아래 블로그를 참고해 주세요.

https://dev.classmethod.jp/articles/jw-download-and-upload-files-from-the-s3-bucket-from-an-ec2-instance/

본 블로그 게시글을 읽고 궁금한 사항이 있으신 분들은 jaewookkim533@yahoo.com로 보내주시면 감사하겠습니다.

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.