跳到內容

Sync Linux Commnad Log to GCP

Scenario

使用 GCP Ops Agent 將 Linux 所下的指令同步到 GCP Log 中留存

流程與說明

  1. 設定 Linux syslog 紀錄 command 功能,將所有 shell 中 command line 紀錄留存
  2. 安裝 GCP Ops Agent 於 Linux 中,須留意 service account 具備 Log Writer 權限
  3. 修改 Ops Agent 設定將 Linux 命令記錄拋轉至 GCP 中

執行步驟

設定 Linux syslog

  • 設定 default profile
/etc/profile.d/bash_log.sh
1
whoami="$(whoami)@$(echo $SSH_CONNECTION | awk '{print $1}')"
2
export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$whoami [$$]: "${PWD/#$HOME/~}" $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"'
  • 設定 rsyslog
/etc/rsyslog.d/bash.conf
1
local6.* /var/log/commands.log
  • 設定完成後重啟服務
Linux console
1
sudo systemctl restart rsyslog
  • 設定 logrotate
/etc/logrotate.d/commands
1
/var/log/commands.log
2
{
3
rotate 4
4
weekly
5
missingok
6
notifempty
7
compress
8
delaycompress
9
sharedscripts
10
postrotate
11
/usr/lib/rsyslog/rsyslog-rotate
12
endscript
13
}
  • 測試 logrotate 設定
Linux console
1
sudo logrotate -d /etc/logrotate.conf

安裝 GCP Ops Agent

  • 留意 GCE 的 service account 要有 Logs Writer 權限
  • 安裝 Ops Agent
Linux console
1
curl -sSO https://dl.google.com/cloudagents/add-google-cloud-ops-agent-repo.sh
2
sudo bash add-google-cloud-ops-agent-repo.sh --also-install
  • 安裝完成後設定 Ops Agent 可依照其他需求,將其他 receivers 加入 GCP Logging
/etc/google-cloud-ops-agent/config.yaml
1
logging:
2
receivers:
3
syslog:
4
type: files
5
include_paths:
6
- /var/log/messages
7
- /var/log/syslog
8
user_command:
9
type: files
10
include_paths:
11
- /var/log/commands.log
12
service:
13
pipelines:
14
default_pipeline:
15
receivers: [syslog, user_command]
  • 重啟 ops agent 服務
Linux console
1
sudo service google-cloud-ops-agent restart

REF