DevOps运维技术栈

利用 rsync 实现俩台liunx服务器数据同步对拷备份转移

rsync命令是一个远程数据同步工具,可通过LAN/WAN快速同步多台主机间的文件。rsync使用所谓的“rsync算法”来使本地和远程两个主机之间的文件达到同步,这个算法只传送两个文件的不同部分,而不是每次都整份传送,因此速度相当快。 rsync是一个功能非常强大的工具,其命令也有很多功能特色选项,我们下面就对它的选项一一进行分析说明。

安装rsync

yum -y install rsync

单条命令介绍

rsync -avz -e ssh /path/to/source/ user@destination:/path/to/destination/

-a:表示以归档模式运行,保留文件属性,递归复制目录。

-v:表示详细模式,显示正在复制的文件。

-z:表示压缩传输,以减少数据传输量。

-e ssh:表示使用 SSH 协议进行安全传输。

/path/to/source/:源目录或文件的路径。

user:用户名,例如root

destination:目的服务器ip地址

/path/to/destination/:目的端的文件路径

为了可以持续运行,实现备份不间断,数据持续对拷

创建一个服务脚本,比如 rsync-service.service

[Unit]
Description=Rsync file synchronization service
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/rsync -avz --delete -e "ssh -i /etc/systemd/system/123_id_rsa"  /path/to/source/ user@destination:/path/to/destination/
Restart=always
[Install]
WantedBy=default.target

Restart=always:确保服务在失败时重新启动

其中:"ssh -i /etc/systemd/system/123_id_rsa" 中的 /etc/systemd/system/123_id_rsa 是ssh密钥的路径

-a:表示以归档模式运行,保留文件属性,递归复制目录。

-v:表示详细模式,显示正在复制的文件。

-z:表示压缩传输,以减少数据传输量。

--delete:该选项表示在目标目录中删除那些源目录中不存在的文件。这是为了确保目标目录是源目录的镜像。注意,使用此选项时需要小心,以防止意外删除重要数据。

-e ssh:表示使用 SSH 协议进行安全传输。

rsync -avz --delete -e "ssh -i /etc/systemd/system/123_id_rsa" /path/to/source/ user@destination:/path/to/destination/

/etc/systemd/system/123_id_rsa:密钥路径

/path/to/source/:源文件路径

user:用户名,例如root

destination:目的服务器ip地址

/path/to/destination/:目的端的文件路径

启用和启动服务

sudo systemctl enable rsync-service.service
sudo systemctl start rsync-service.service

停止禁用服务

sudo systemctl stop rsync-service.service

sudo systemctl disable rsync-service.service

退出移动版