需求:
每天有调度任务执行,会产生大量log等文件。导致服务器空间报警不足。又不能直接rm掉。所以压缩后弄到备份机器上。
log目录多如:
根据文件名匹配出6个月前的文件。进行压缩备份。并rm掉以省出空间。
压缩后:
脚本描述:
work_path:自动获取当前文件所在绝对路径;
set timeout:expect的超时时间。单位S,设置-1时为永不超时。
#clear six months ago files to tar and scp... echo "Please wait..." work_path=$(dirname $(readlink -f $0)) #get now_path fileEnd=${work_path##*/}; m=`date -d "6 months ago" +%Y%m` #now=`date -d "0 months ago" +%Y%m` index=0 f=`ls $work_path -1 -c` for name in $f do n=`expr "$name" : '.*\([0-9]\{8\}\).*'` if [ "$n" != "" ] && [ "$n" -le "$m"31 ] then f[$index]="$work_path/$name" else f[$index]="" fi (( index ++ )) done str=${f[@]} if [ "${#str}" -gt 0 ] then tar -zcvf $work_path/logbak_$m.tar.gz $str && rm -rf $str echo "tar.gz finished!" else echo "No files found." exit 0 fi echo "tar.gz maked, now delete old files." #rm -fr $str echo "rm finished,start scp to ptfLogsBackup" backupMachine=你的远程备份ip; backupMachinePath=备份ip的目的path; set timeout 300 ##if bak_file not exists,creating... /usr/bin/expect<<EOF spawn ssh 远程ip的username@$backupMachine "\[ -d $backupMachinePath/$fileEnd \] && echo ok, file exists.. || mkdir -p $backupMachinePath/$fileEnd" expect "password:" send "远程ip的password\r" expect EOF EOF #scp sending... /usr/bin/expect<<EOF spawn bash -c "scp -r $work_path/*.tar.gz 远程ip的username@$backupMachine:$backupMachinePath/$fileEnd && rm -rf $work_path/*.tar.gz" expect "password:" send "远程ip的password\r" expect EOF EOF echo "scp tar.gz files finished!" echo "done." exit 0
参考:
了解shell中、、有的地方写的有点烂。每天学习一点