阅读更多
#### 最近遇到一个情况就是服务器不响应了,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 root@$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 root@$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 root@$HOST:$REMOTE_LOG_FILE $LOCAL_LOG_PATH
fi
log "Delete $REMOTE_LOG_FILE from $HOST"
ssh root@$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公钥上传到服务器,好免密码登录,执行命令