10

Linux下自动删除过期备份和自动异地备份 - YoungQ

 1 year ago
source link: https://www.cnblogs.com/young-q/p/16673474.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

每天自动删除过期备份

首先编写一个简单的Shell脚本DeleteExpireBackup.sh

#!/bin/bash

# 修改需要删除的路径
location="/database/backup/"

# 删除最后修改时间为30天以前的备份文件夹
find $location -mtime +30 -type d | xargs rm -rf {} 
  • -mtime:文件内容最后一次修改的时间,+30 代表大于30天的。其他参数可选:

    • 访问时间戳(atime):最后一次读取文件的时间。

    • 更改时间戳 (ctime):上次更改文件元数据的时间,例如其所有权、位置、文件类型和权限设置。

  • -type代表文件类型,f代表文件,d代表目录,l代表软链接文件

脚本编写并保存后会发现无法执行,因为需要设置文件权限,切换到脚本保存的当前目录,执行下面的命令:

chmod a+x DeleteExpireBackup.sh

脚本准备完毕,然后就是设置自动执行时间

我这里偷懒了,直接用的宝塔设置的,其实本质是一样的,都是用的crontab定时执行,不懂的同学自行google。

宝塔设置如下:

1736726-20220909171228987-873070526.png

设置完成后,点击添加任务,自动删除备份就完成了。

有时候执行脚本会出现以下错误:
/bin/bash^M: 坏的解释器: 文本文件忙

出现这个错误,多半是Windows下编写的脚本,编写完毕后传到服务器上执行。

因为Windows系统下换行符为 \r\n,linux下换行符为 \n,因此在windows下编写的文件会比linux下多一个回车符号 \r。去掉多余的 \r 回车符 即可。

操作办法:可以用sed命令进行全局替换 sed 's/\r//' -i 脚本名称.sh

每天定时异地备份

其余操作和定时删除大同小异,所以这里我只展示脚本内容:

#!/usr/bin/expect -f
# 获取当前日期 例如:20220101
set date [ clock format [ clock seconds ] -format "%Y%m%d" ] 
# 传输用户名
set username 用户名
# 密码
set password 密码
#  expect默认timeout为30S  超过30s未传输完会停止,设置为 -1 则不限制超时时间
set timeout -1

#                  压缩  端口  递归 需要传输的本地绝对路径              用户名     目标IP       目标服务器路径
 spawn  /usr/bin/scp -C -P 22 -r /database/backup/$date/ [email protected]:/database/backup/

expect  {
"*yes/no" {send "yes\r";exp_continue}
"*password:" {send "$password\r"}
}

expect eof

脚本是使用 scp 从一个Linux传送至另一台Linux服务器来完成异地备份的。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK