我正在编写一个备份 bash 脚本,它可以执行许多耗时较长的rsync
任务。有些任务每次最多需要 3 到 4 个小时。
在这些大型传输之后,我希望在同步文件后刷新磁盘缓存,然后在目标磁盘上运行一些校验和,以确保目标磁盘上的所有内容都已备份好。下面这行代码据说可以做到这一点,需要sudo
:
sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches'
为了不间断地完成整个 bash 脚本,我在开始时要求输入用户密码sudo
,但我注意到sudo
可以理解的是,密码会话仅持续了 15 分钟左右。几个小时后,脚本停止等待用户sudo
再次输入密码。
运行此脚本的最佳方法是什么,以sudo
在需要时保留权限,但无需每次都请求密码,以便脚本可以不间断地运行几个小时,并保留磁盘缓存刷新命令的能力?
#!/bin/bash
# backup all drives using rsync and also verify the integrity of the backup
# BACKUP
# first, drop the disks internal volatile caches to start with clean file system state (https://unix.stackexchange.com/questions/30970/)
printf "\nNeed sudo priviliges in order to flush disk caches in this script.\n"
# invoke sudo to ask for permission needed to clear the disk cache in next command
sudo printf "\nClearing disk cache... "
sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches'
printf "DONE.\n\n\n"
# now run the backup lines
# First disk
printf "rsync 'First' disk...\n"
# need to put [] around $ to escape it for folders like $RECYCLE.BIN (https://stackoverflow.com/questions/19305010)
rsync -vah --progress --stats --exclude={"Adobe","[$]RECYCLE.BIN","System Volume Information","pagefile.sys","temp"} /media/n/First/ ./First/
printf "\n\n"
# Scratch disk
printf "rsync 'Scratch' disk...\n"
rsync -vah --progress --stats --exclude={"[$]RECYCLE.BIN","System Volume Information","pagefile.sys","temp"} /media/n/Scratch/ ./Scratch/
printf "\n\n"
# ...
# CHECKSUM
# re-read/compare
# drop the disks internal volatile caches
printf "Now testing backup checksums for integrity.\n\n"
# rsync --itemize-changes, legend here: (https://stackoverflow.com/questions/4493525)
# First disk
printf "Clearing disk cache... "
sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches'
printf "DONE.\n"
printf "Checking 'First' disk backup...\n"
# need to put [] around $ to escape it for folders like $RECYCLE.BIN (https://stackoverflow.com/questions/19305010)
rsync -vah --progress --checksum --itemize-changes --stats --exclude={"Adobe","[$]RECYCLE.BIN","System Volume Information","pagefile.sys","temp"} /media/n/First/ ./First/
printf "\n\n"
# ...
print "Finished.\n\n"
# revoke sudo
sudo -k
exit
答案1
使用 sudo 运行你的脚本。
sudo yourscript.sh
只需询问您一次,脚本就会以 root 权限运行。
答案2
使用(以 root 身份)visudo(或直接编辑 /etc/sudoers)并添加:
# below "root ALL=..."
jonny ALL=NOPASSWD: your_script
注意:该脚本必须位于 /etc/sudoers 中的“secure_path”之一中