# Rsync

##### 限制頻寬

限制傳檔的網路頻寬

```bash
--bwlimit=30000
```

> 30000 = 30000 KB/ps = 30 MB/ps

##### Dry Run

```bash
rsync -avh -n <source> <destination>
```

##### 檔案與資料夾同步

本機內不同個資料夾做複製或同步

```bash
rsync -avh --delete --exclude='path1/to/exclude' --exclude='path2/to/exclude' source/ destination
rsync -avh /source/*.log /destination
```

- source/ 來源目錄+斜線 會複製目錄內的內容
- source 來源目錄不加斜線 會複製整個目錄
- --delete 來源檔案被刪除時也會同步到目的端 (*NOTE: 如果來源位置不是目錄，而是檔案 \*.log， 即使來源檔案被刪除，已同步的目的檔案仍會保留*)

##### 進度條

遠端複製大檔案需要續傳與進度條

```bash
rsync --partial --progress --rsh=ssh <local_file> user@host:<remote_file>
```

##### 遠端同步

本機至遠端

```bash
rsync -avzh /root/rpmpkgs root@192.168.0.141:/root/
```

遠端至本機

```bash
rsync -avzh root@192.168.0.141:/root/rpmpkgs /tmp/myrpms
```

透過 SSH

```bash
# Copy a File from a Remote Server to a Local Server
rsync -avzhe ssh root@192.168.0.141:/root/anaconda-ks.cfg /tmp

# Copy a File from a Local Server to a Remote Server
rsync -avzhe ssh backup.tar.gz root@192.168.0.141:/backups/
```

##### Include &amp; Exclude

指定附檔名

```bash
rsync -avh /source/*.log /destination

rsync -avh --include='*.log' --exclude='*' /source/ /destination
```

例外檔案清單

```bash
rsync -avh --exclude-from=/root/exclude-files.txt /source/ /destination
```

##### 複製整個系統

複製 Linux 整個系統

- [How to Clone a CentOS Server with Rsync](https://www.tecmint.com/clone-centos-server/)
- [How To Backup Your Entire Linux System Using Rsync](https://ostechnix.com/backup-entire-linux-system-using-rsync/)

```bash
mount /dev/sdb1 /mnt
rsync -aAXv / --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found"} /mnt
```

With a exclusion file

exclude-files.txt:

```
/boot
/dev
/tmp
/sys
/proc
/backup
/etc/fstab
/etc/mtab
/etc/mdadm.conf
/etc/sysconfig/network*
```

Cloning a Linux Server

```bash
sudo rsync -vPa -e 'ssh -o StrictHostKeyChecking=no' --exclude-from=/root/exclude-files.txt / REMOTE-IP:/
```

##### How does rsync work

[https://michael.stapelberg.ch/posts/2022-07-02-rsync-how-does-it-work/](https://michael.stapelberg.ch/posts/2022-07-02-rsync-how-does-it-work/)

##### Other solutions

- [Syncthing](https://github.com/syncthing/syncthing) - It is a free and open-source file syncing application used to sync files between multiple remote devices over the internet. It works on peer-to-peer architecture and exchanges the data automatically between two devices. 
    - [How to Install Syncthing Remote File Synchronization Software on Debian 11](https://www.howtoforge.com/how-to-install-syncthing-on-debian-11/)