Two Linux servers back up each other's files (sshpass + crontab)

crontab

Crontab is the scheduled scheduling software that comes with the Linux system. It can be used to set instructions to be executed periodically. It is generally used to run jobs during non-peak load periods every day, and can run jobs without manual intervention. Supports running at different times of the week or month.
The crontab command allows users to submit, edit or delete corresponding jobs. Each user can have a crontab file to save scheduling information. For server backup files, we need to use crontab to perform periodic backup work.

sshpass

sshpass allows you to connect to a remote host via SSH and execute commands without entering a password directly. Compared with manually entering credentials, sshpass avoids manually entering passwords and improves the execution efficiency of automated processes. To back up files between two servers, you need to use sshpass to connect and transfer files.

step

1. Create an sh file as follows:

#!/bin/sh
source /etc/profile

#设置备份的源文件夹
backup_source=/home/admin/sh
#设置目的服务器地址 
remote_username=admin
remote_ip=10.10.11.60
remote_password=qwer123
remote_folder=/home/admin/sk
 
 
#创建备份的缓存文件夹backup_home
backup_home=/home/admin/backup_home
if [ ! -d ${backup_home} ];then
    mkdir ${backup_home}
    if [ $? -eq 0 ]; then
        echo "缓存文件夹创建成功"
    else
        echo "缓存文件夹创建失败"
        exit 1
    fi
else
    echo "缓存文件夹已经存在"
fi
 
#压缩文件到backup_home
date=$(date +%Y%m%d)
zip -q -r ${backup_home}/${date}.zip ${backup_source}
if [ $? -eq 0 ]; then
    echo "文件压缩成功"
else
    echo "文件压缩失败"
    exit 1
fi
 
#从本地复制到远程
sshpass -p ${remote_password} scp ${backup_home}/${date}.zip ${remote_username}@${remote_ip}:${remote_folder} 
if [ $? -eq 0 ]; then
    echo "从本地复制到远程成功"
else
    echo "从本地复制到远程失败"
    exit 1
fi
 
#删除backup_home下超过7天的zip文件
find ${backup_home} -mtime +7 -name "*.zip" -exec rm -rf {} \;

This is an executable sh file. Note: After the file is created, you need to use chmod to authorize the file as an "executable file", as follows:

//test.sh 是文件名
chmod +x test.sh

2. Install sshpass

yum install sshpass

3. Add the sh command file to the crontab run cycle

//添加周期性任务
crontab -e

//进入编辑状态
35 * * * * /home/admin/sd/test.sh >> /home/admin/backup_home/log.txt

//重启crontab
systemctl restart crond.service

4. Authorize servers to transfer files to each other.

 Note: This step cannot be omitted. Otherwise, when crontab performs the task, the file transfer will fail due to unauthorized access. Be sure to authorize it first, and then let crontab start the backup task.

Results display:

 

Acho que você gosta

Origin blog.csdn.net/yx1166/article/details/132323107
Recomendado
Clasificación