shell自動下載nginx日誌檔案到本地
阿新 • • 發佈:2018-12-26
最近遇到一個情況就是伺服器不響應了,nginx也不寫日誌,經查發現是日誌檔案太大多,磁碟滿了,以前都是用指令碼自動上傳到OSS的,現在需要將log下載到本地,於是用shell寫了一段指令碼,然後放到crontab裡面,每天凌晨把log下載下來
shell 指令碼
#!/bin/bash
HOST="115.114.113.112"
LOG_PATH="/usr/local/nginx/logs/"
LOCAL_LOG_PATH="/home/admin/logs/$HOST/"
# 把所有帶日期的日誌檔案,同步本地,然後刪除遠端檔案
# 日誌檔案命名: access_2016-12-28.log
LOGS=$(ssh [email protected]$HOST ls $LOG_PATH | grep _)
LOGS=${LOGS// / }
function log() {
echo `date "+%Y-%m-%d %H:%M:%S"` $1
}
for log in $LOGS
do
REMOTE_LOG_FILE="$LOG_PATH$log"
LOCAL_LOG_FILE="$LOCAL_LOG_PATH$log"
log "Ready to download from $HOST >> $REMOTE_LOG_FILE"
log "Check local $LOCAL_LOG_FILE exists"
DOWNLOAD=1
if [ -f $LOCAL_LOG_FILE ]; then
log "Local file already exists, and check the md5 value of the file"
REMOTE_FILE_MD5=$(ssh [email protected]$HOST md5sum $REMOTE_LOG_FILE | awk '{print $1}')
LOCAL_FILE_MD5=$(md5sum $LOCAL_LOG_FILE | awk '{print $1}' )
# log "$REMOTE_FILE_MD5 == $LOCAL_FILE_MD5"
if [ "$REMOTE_FILE_MD5"x = "$LOCAL_FILE_MD5"x ]; then
DOWNLOAD=0
log "The file content is the same, skip the current file"
else
log "The file content is different, to download the file"
fi
fi
if [ $DOWNLOAD = 1 ]; then
log "Download $REMOTE_LOG_FILE from $HOST"
scp [email protected]$HOST:$REMOTE_LOG_FILE $LOCAL_LOG_PATH
fi
log "Delete $REMOTE_LOG_FILE from $HOST"
ssh [email protected]$HOST rm $REMOTE_LOG_FILE
done
給指令碼執行許可權
$ chmod +x sync_115.114.113.112.sh
加到crontab,每天凌晨一分執行,因為伺服器上面0分會生成日誌檔案,所以這裡等一分鐘再下載,基本就沒有問題
1 0 * * * /home/admin/logs/sync_115.114.113.112.sh
這裡需要注意的是,需要提前把ssh公鑰上傳到伺服器,好免密碼登入,執行命令