1.确保有openssh服务,没有请安装
1 |
sudo apt-get install openssh-server |
2.添加用户组
1 |
groupadd -g 502 sftp |
3.添加用户
1 2 |
useradd -g sftp -d /home/hs -m -u 502 hs usermod -s /usr/lib/sftp-server hs #为安全起见,该用户不能使用shell只能使用sftp命令 |
4.在客户端生成密钥
1 |
ssh-keygen -t [rsa|dsa] |
文件生成在/home/monica/.ssh中。
后缀为.pub需发送到服务器,并执行命令
1 |
cat id_dsa.pub >> /home/hs/.ssh/authorized_keys |
5.编写脚本
此脚本将备份/home/monica/test中的attachments report_attachments中的文件,备份文件分别在/backup/attachments和/backup/report_attachments中,以.tgz文件格式保存。删除7天前的备份文件,并至少保留2个备份。tgz文件将传送到/home/hs/backupfile中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
#!/bin/bash #tar -zvxf *.tgz #日志路径 LogFile="/backup/backup.log" SourceDir="/home/monica/test/" BakDir=/backup RetainDay=7 RetainPiece=2 #ProjectLst=/backup/project.lst PROJECTLIST="attachments report_attachments" DATE=`date +"%Y%m%d%H"` echo "">>$LogFile echo "backup start at $(date +"%Y-%m-%d %H:%M:%S")" >>$LogFile echo "--------------------------------------------------" >>$LogFile #cd $BakDir #PROJECTLIST=`cat $ProjectLst` for Project in $PROJECTLIST do [ ! -d $BakDir/$Project ] && mkdir -p $BakDir/$Project cd $BakDir/$Project ProjectData=$SourceDir/$Project DestDir=$BakDir/$Project/$Project$DATE PackFile=$DATE.$Project.tgz if [ -f $BakDir/$Project/$PackFile ] then echo "backup file $BakDir/$Project/$PackFile has existed !" >>$LogFile else cp -RHpf $ProjectData $DestDir >/dev/null tar -zcvf $PackFile $Project$DATE >/dev/null echo "backup $Project done into $PackFile" >>$LogFile rm -rf $Project$DATE sftp -i /home/monica/.ssh/id_rsa -oPort=24 backupuser@192.168.0.1 <<END_SFTP cd backupfile put $PackFile exit END_SFTP echo "Packfile $PackFile has been transferred.">>$LogFile fi BakFileCount=`ls -l *.tgz|wc -l` WillDeleteFileCount=`find $BakDir/$Project/*.tgz -type f -mtime +$RetainDay|wc -l` if [ ${RetainPiece} -lt ${BakFileCount} ] && [ ${WillDeleteFileCount} -lt ${BakFileCount} ] then echo "Files below will be deleted.">>$LogFile find $BakDir/$Project/*.tgz -type f -mtime +$RetainDay >>$LogFile find $BakDir/$Project/*.tgz -type f -mtime +$RetainDay -exec rm {} \; >/dev/null echo "Files backed up $RetainDay days agon have been deleted.">>$LogFile else echo "Only "$RetainPiece" Pieces of backup file.">>$LogFile fi done echo "--------------------------------------------------" >>$LogFile echo "backup end at $(date +"%Y-%m-%d %H:%M:%S")" >>$LogFile exit 0 |
原文链接:sftp自动备份文件,转载请注明来源!