Files
StudyDiary/02-学习笔记/要使用 `rsync` 同步数据后保证恢复时权限和属性与原始.md
2026-07-23 20:36:13 +08:00

129 lines
3.4 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: 要使用 `rsync` 同步数据后保证恢复时权限和属性与原始
created: 2026-05-31
source: Cherry Studio
tags:
---
要使用 `rsync` 同步数据后保证恢复时权限和属性与原始一致,需要使用正确的参数来保留**所有权、权限、时间戳等元数据**。以下是不同场景下的解决方案:
---
### **1\. 超级用户(Root)恢复(源和目标均为Root权限)**
如果需要完全恢复**用户、组、权限、时间戳**等元数据,必须使用 `root``sudo` 运行:
```bash
sudo rsync -avAXH --numeric-ids --delete /source/ user@remote:/destination/
```
**关键参数说明:**
- `-a` (`--archive`):递归同步并保留权限、所有者、时间戳等
- `-v` (`--verbose`):输出详细信息
- `-A` (`--acls`):保留ACLs(访问控制列表)
- `-X` (`--xattrs`):保留扩展属性(如SELinux标签)
- `-H` (`--hard-links`):保留硬链接
- `--numeric-ids`:以数字形式保留用户/组ID(不依赖目标机器的用户名映射)
- `--delete`:删除目标端存在但源端不存在的内容(完全一致恢复)
---
### **2\. 非Root用户恢复(仅保留部分权限)**
如果源数据 **不是** root 所有,或者目标服务器 **不信任** root 访问,可以仅保留可管理的权限:
```bash
rsync -av --no-perms --no-owner --no-group --times /source/ user@remote:/destination/
```
或(部分保留):
```bash
rsync -rtlgoDv --no-perms --no-owner /source/ user@remote:/destination/
```
**参数说明:**
- `--no-perms``--no-owner``--no-group`:跳过权限和所有权(非root用户无法修改这些)
- `--times` (`-t`):仅保留时间戳
- `-D`:保留设备文件(仅限root
- `-o` (`--owner`)、`-g` (`--group`):尝试保留用户/组(可能仅在root下有效)
---
### **3\. 跨服务器同步的完整权限保障方案**
如果既要同步数据,又想 **以后能完整恢复**(即使源服务器崩溃),最佳方式是:
1. **备份元数据**(先存一份权限信息,以防后续恢复):
```bash
getfacl -R /source/ > /backup/source_permissions.acl
```
2. **用** `rsync` **完整同步数据**
```bash
sudo rsync -avAXH --numeric-ids --delete /source/ user@remote:/destination/
```
3. **恢复时重新应用权限**
```bash
sudo setfacl --restore=/backup/source_permissions.acl
```
---
### **4\. 限制非Root权限的方案**
如果源数据 **有 root 权限部分**,但目标机器 **不能使用 root**,可以采用:
1. **只同步你能控制的文件**
```bash
rsync -av --rsync-path="sudo -u targetuser rsync" \
--filter="- *root*" /source/ user@remote:/destination/
```
2. **使用** `fakeroot`**(模拟root权限)**(仅适用于部分环境):
```bash
fakeroot rsync -av /source/ user@remote:/destination/
```
3. **在恢复时手动修复权限**(适用于少量文件):
```bash
chmod/chown 手工调整权限
```
---
### **总结**
| 方案 | 适用场景 | 能否100%恢复权限 |
| --- | --- | --- |
| **root+**`-aAXH` | 需要完整恢复 | ✅ 可以 |
| `--numeric-ids` | 跨机器同步 | ✅ 可以 |
| **非root** `rsync` | 受限权限 | ❌ 部分丢失 |
| **ACL备份+恢复** | 安全恢复 | ✅ 可以 |
如果数据是关键业务,建议 **先测试恢复流程**,确保 `rsync` 参数正确,避免权限丢失!