sftp自动备份文件

  • Post author:
  • Post category:其他

1.sudo apt-get install openssh-server

2.groupadd -g 502 sftp

3.useradd -g sftp -d /home/hs -m -u 502 hs

usermod -s /usr/lib/sftp-server hs#为安全起见,该用户不能使用shell只能使用sftp命令

4.在客户端生成密钥。

ssh-keygen -t [rsa|dsa]

文件生成在/home/monica/.ssh中。

后缀为.pub需发送到服务器,并执行命令#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中。

#!/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

版权声明:本文为Kenny0502原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。