- Команда Rsync в Linux с примерами
- Установка Rsync
- Установите Rsync в Ubuntu и Debian
- Установите Rsync на CentOS и Fedora
- Синтаксис команды Rsync
- Базовое использование Rsync
- Использование rsync для синхронизации данных с / на удаленную машину
- Исключить файлы и каталоги
- Выводы
- 10 Practical Examples of Rsync Command in Linux
- Some Advantages and Features of Rsync Command
- Install Rsync in Linux System
- 1. Copy/Sync Files and Directory Locally
- 2. Copy/Sync Files and Directory to or From a Server
- 3. Rsync Over SSH
- 4. Show Progress While Transferring Data with rsync
- 5. Use of –include and –exclude Options
- 6. Use of –delete Option
- 7. Set the Max Size of Files to be Transferred
- 8. Automatically Delete source Files After Successful Transfer
- 9. Do a Dry Run with rsync
- 10. Rsync Set Bandwidth Limit and Transfer File
- If You Appreciate What We Do Here On TecMint, You Should Consider:
Команда Rsync в Linux с примерами
rsync — это быстрая и универсальная утилита командной строки для синхронизации файлов и каталогов между двумя местоположениями через удаленную оболочку или с / на удаленный демон Rsync. Он обеспечивает быструю инкрементную передачу файлов, передавая только различия между источником и местом назначения.
Rsync можно использовать для зеркального отображения данных, инкрементного резервного копирования, копирования файлов между системами, а также в качестве замены команд scp , sftp и cp .
В этой статье объясняется, как использовать rsync на практических примерах и подробных объяснениях наиболее распространенных параметров rsync .
Установка Rsync
Утилита rsync предустановлена в большинстве дистрибутивов Linux и macOS. Если в вашей системе не установлен rsync , вы можете легко установить его с помощью диспетчера пакетов вашего дистрибутива.
Установите Rsync в Ubuntu и Debian
Установите Rsync на CentOS и Fedora
Синтаксис команды Rsync
Прежде чем перейти к использованию команды rsync , давайте начнем с обзора основного синтаксиса.
Выражения утилиты rsync имеют следующую форму:
- OPTION — параметры rsync .
- SRC — Исходный каталог.
- DEST — целевой каталог.
- USER — удаленное имя пользователя.
- HOST — удаленное имя хоста или IP-адрес.
rsync предоставляет ряд параметров, управляющих поведением команды. Наиболее широко используемые варианты:
- -a , —archive , режим архива, эквивалент -rlptgoD . Этот параметр указывает rsync рекурсивно синхронизировать каталоги, передавать специальные и блочные устройства, сохранять символические ссылки, время модификации, группы, владение и разрешения.
- -z , —compress . Эта опция заставляет rsync сжимать данные при их отправке на конечный компьютер. Используйте эту опцию, только если подключение к удаленному компьютеру медленное.
- -P , что эквивалентно —partial —progress . Когда используется эта опция, rsync показывает индикатор выполнения во время передачи и сохраняет частично переданные файлы. Это полезно при передаче больших файлов по медленным или нестабильным сетевым соединениям.
- —delete . Когда используется эта опция, rsync удаляет посторонние файлы из места назначения. Это полезно для зеркалирования.
- -q , —quiet . Используйте эту опцию, если вы хотите подавить сообщения, не связанные с ошибками.
- -e . Эта опция позволяет вам выбрать другую удаленную оболочку. По умолчанию rsync настроен на использование ssh.
Базовое использование Rsync
Самый простой вариант использования rsync — это копирование одного файла из одного в другое локальное расположение. Вот пример:
Пользователь, выполняющий команду, должен иметь разрешения на чтение в исходном местоположении и разрешения на запись в месте назначения.
Если пропустить имя файла из места назначения, файл будет скопирован с текущим именем. Если вы хотите сохранить файл под другим именем, укажите новое имя в целевой части:
Настоящая мощь rsync проявляется в синхронизации каталогов. В приведенном ниже примере показано, как создать локальную резервную копию файлов веб-сайта:
Если целевой каталог не существует, rsync создаст его.
Стоит отметить, что rsync разному обрабатывает исходные каталоги с помощью завершающей косой черты ( / ). Если исходный каталог имеет косую черту в конце, команда скопирует только содержимое каталога в целевой каталог. Если косая черта в конце опущена, rsync копирует исходный каталог в целевой каталог.
Использование rsync для синхронизации данных с / на удаленную машину
При использовании rsync для удаленной передачи данных его необходимо установить как на исходном, так и на целевом компьютере. Новые версии rsync настроены на использование SSH в качестве удаленной оболочки по умолчанию.
В следующем примере мы переносим каталог с локального компьютера на удаленный:
Чтобы передать данные с удаленного компьютера на локальный, используйте удаленное местоположение в качестве источника:
Если SSH на удаленном хосте прослушивает порт, отличный от порта по умолчанию 22, укажите порт с помощью параметра -e :
При передаче больших объемов данных рекомендуется запускать команду rsync внутри сеанса экрана или использовать параметр -P :
Исключить файлы и каталоги
Есть два варианта исключения файлов и каталогов. Первый вариант — использовать аргумент —exclude и указать файлы и каталоги, которые вы хотите исключить, в командной строке.
При исключении файлов или каталогов необходимо использовать их относительные пути к исходному местоположению.
В следующем примере показано, как исключить node_modules и tmp :
Второй вариант — использовать параметр —exclude-from и указать файлы и каталоги, которые вы хотите исключить из файла.
Выводы
Мы показали вам, как использовать Rsync для копирования и синхронизации файлов и каталогов. Еще больше информации о Rsync можно найти на странице руководства пользователя Rsync .
Не стесняйтесь оставлять комментарии, если у вас есть вопросы.
Источник
10 Practical Examples of Rsync Command in Linux
Rsync (Remote Sync) is the most commonly used command for copying and synchronizing files and directories remotely as well as locally in Linux/Unix systems.
With the help of the rsync command, you can copy and synchronize your data remotely and locally across directories, disks, and networks, perform data backups, and mirror between two Linux machines.
Rsync Local and Remote File Synchronization
This article explains 10 basic and advanced usage of the rsync command to transfer your files remotely and locally in Linux-based machines. You don’t need to be a root user to run the rsync command.
Some Advantages and Features of Rsync Command
- It efficiently copies and sync files to or from a remote system.
- Supports copying links, devices, owners, groups, and permissions.
- It’s faster than scp (Secure Copy) because rsync uses a remote-update protocol which allows transferring just the differences between two sets of files. The first time, it copies the whole content of a file or a directory from source to destination but from next time, it copies only the changed blocks and bytes to the destination.
- Rsync consumes less bandwidth utilization as it uses compression and decompression method while sending and receiving data on both ends.
The basic syntax of the rsync command
Some common options used with rsync commands
- -v : verbose
- -r : copies data recursively (but don’t preserve timestamps and permission while transferring data.
- -a : archive mode, which allows copying files recursively and it also preserves symbolic links, file permissions, user & group ownerships, and timestamps.
- -z : compress file data.
- -h : human-readable, output numbers in a human-readable format.
Install Rsync in Linux System
We can install the rsync package with the help of the following command in your Linux distribution.
1. Copy/Sync Files and Directory Locally
Copy/Sync a File on a Local Computer
The following command will sync a single file on a local machine from one location to another location. Here in this example, a file name backup.tar needs to be copied or synced to /tmp/backups/ folder.
In the above example, you can see that if the destination is not already existed rsync will create a directory automatically for the destination.
Rsync Local Files
Copy/Sync a Directory on Local Computer
The following command will transfer or sync all the files from one directory to a different directory in the same machine. Here in this example, /root/rpmpkgs contains some rpm package files and you want that directory to be copied inside /tmp/backups/ folder.
Rsync Local Directory
2. Copy/Sync Files and Directory to or From a Server
Copy a Directory from Local Server to a Remote Server
This command will sync a directory from a local machine to a remote machine. For example, there is a folder in your local computer “rpmpkgs” that contains some RPM packages and you want that local directory’s content sends to a remote server, you can use the following command.
Rsync Directory Remote System
Copy/Sync a Remote Directory to a Local Machine
This command will help you sync a remote directory to a local directory. Here in this example, a directory /root/rpmpkgs which is on a remote server is being copied in your local computer in /tmp/myrpms.
Rsync Remote Directory to Local
3. Rsync Over SSH
With rsync, we can use SSH (Secure Shell) for data transfer, using SSH protocol while transferring our data you can be ensured that your data is being transferred in a secured connection with encryption so that nobody can read your data while it is being transferred over the wire on the internet.
Also when we use rsync we need to provide the user/root password to accomplish that particular task, so using the SSH option will send your logins in an encrypted manner so that your password will be safe.
Copy a File from a Remote Server to a Local Server with SSH
To specify a protocol with rsync you need to give the “-e” option with the protocol name you want to use. Here in this example, We will be using the “ssh” with the “-e” option and perform data transfer.
Rsync Copy Remote File to Local
Copy a File from a Local Server to a Remote Server with SSH
4. Show Progress While Transferring Data with rsync
To show the progress while transferring the data from one machine to a different machine, we can use the ‘–progress’ option. It displays the files and the time remaining to complete the transfer.
Rsync Progress While Copying Files
5. Use of –include and –exclude Options
These two options allow us to include and exclude files by specifying parameters with these option helps us to specify those files or directories which you want to include in your sync and exclude files and folders with you don’t want to be transferred.
Here in this example, the rsync command will include those files and directory only which starts with ‘R’ and exclude all other files and directory.
Rsync Include and Exclude Files
6. Use of –delete Option
If a file or directory does not exist at the source, but already exists at the destination, you might want to delete that existing file/directory at the target while syncing.
We can use the ‘–delete‘ option to delete files that are not there in the source directory.
Source and target are in sync. Now create a new file test.txt at the target.
Target has the new file called test.txt, when synchronizing with the source with the ‘–delete‘ option, it removed the file test.txt.
Rsync Delete Option
7. Set the Max Size of Files to be Transferred
You can specify the Max file size to be transferred or sync. You can do it with the “–max-size” option. Here in this example, the Max file size is 200k, so this command will transfer only those files which are equal to or smaller than 200k.
Rsync Set Max File Transfer Size
8. Automatically Delete source Files After Successful Transfer
Now, suppose you have the main web server and a data backup server, you created a daily backup and synced it with your backup server, now you don’t want to keep that local copy of backup in your web server.
So, will you wait for the transfer to complete and then delete that local backup file manually? Of Course NO. This automatic deletion can be done using the ‘–remove-source-files‘ option.
Rsync Delete Source File After Transfer
9. Do a Dry Run with rsync
If you are a newbie using rsync and don’t know what exactly your command going to do. Rsync could really mess up the things in your destination folder and then doing an undo can be a tedious job.
Use of this option will not make any changes to the files and shows the output of the command, if the output shows exactly the same you want to do then you can remove the ‘–dry-run‘ option from your command and run on the terminal.
Rsync Dry Run
10. Rsync Set Bandwidth Limit and Transfer File
You can set the bandwidth limit while transferring data from one machine to another machine with the the help of ‘–bwlimit‘ option. This option helps us to limit I/O bandwidth.
Also, by default rsync syncs changed blocks and bytes only, if you want explicitly want to sync the whole file then you use the ‘-W‘ option with it.
That’s all with rsync now, you can see man pages for more options. Stay connected with Tecmint for more exciting and interesting tutorials in the future. Do leave your comments and suggestions.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник