Windows rsync with ssh

Как копировать файлы при помощи Rsync через SSH

1 . Установка публичных ключей SSH

Для начала нужно сгенерировать открытые ключи SSH без пароля на первоначальном сервере:

/.ssh/id_rsa -q -P «»
cat

Это открытый SSH-ключ, который можно разместить на других хостах, чтоб получить доступ:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDLVDBIpdpfePg/a6h8au1HTKPPrg8wuTrjdh0QFVPpTI4KHctf6/FGg1NOgM++hrDlbrDVStKn/b3Mu65//tuvY5SG9sR4vrINCSQF++a+YRTGU6Sn4ltKpyj3usHERvBndtFXoDxsYKRCtPfgm1BGTBpoSl2A7lrwnmVSg+u11FOa1xSZ393aaBFDSeX8GlJf1SojWYIAbE25Xe3z5L232vZ5acC2PJkvKctzvUttJCP91gbNe5FSwDolE44diYbNYqEtvq2Jt8x45YzgFSVKf6ffnPwnUDwhtvc2f317TKx9l2Eq4aWqXTOMiPFA5ZRM/CF0IJCqeXG6s+qVfRjB root@cloudads

Скопируйте данный ключ в буфер обмена и подключитесь к серверу назначения.

Поместите этот ключ в файл

Если папки SSH не существует, создайте ее вручную:

/.ssh/authorized_keys
chmod 0644

2. Файлы Rsync

Rsync – очень полезная утилита, так как она, помимо всего прочего, позволяет пользователю рекурсивно копировать файлы по зашифрованному каналу с применением сжатия.

Скопируем файл, находящийся в /root/bigfile.txt на первоначальном сервере (198.211.117.101), на сервер назначения (IP: 198.211.117.129) и также сохраним его в /root/bigfile.txt.

Войдите на исходный сервер и, применив утилиту rsync на указанный файл, скопируйте его на сервер назначения:

rsync -avz -e «ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null» —progress /root/bigfile.txt 198.211.117.129:/root/

Если вы работаете с другого пользователя, например, с «username», нужно добавить его перед сервером назначения. Убедитесь, что открытый ключ помещен в файле

/.ssh/authorized_keys данного пользователя:

rsync -avz -e «ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null» —progress /root/bigfile.txt username@198.211.117.129:/

Параметры SSH помогут сдерживать Rsync, а также избежать Rsync-указаний при каждом подключении к новому серверу.

Убедитесь, что файл был скопирован на целевой сервер (198.211.117.129):

Rsync через ssh

У нас есть два сервера:

1) 1.1.1.1 — основной сервер (файлы, почта, что угодно иное), пользователь user1.
2) 2.2.2.2 — сервер, на котором хранятся резервные копии, пользователь user2.

Считаем, что раньше вы не настраивали доступ по ssh к серверам по ключам, а используете пароли. Заодно от паролей избавимся.

Идея: находясь на сервере 2.2.2.2, мы запускаем процесс копирования данных с основного сервера 1.1.1.1 (к себе, на 2.2.2.2).

Проверяем коннект ssh с паролем

Если мы с сервера 2.2.2.2 не сможем с паролем соединиться по ssh к 1.1.1.1, то дальше можно и не продолжать.

Готовим почву

На серверах установим rsync:

yum install xinetd rsync

Редактируем конфиг xinetd для rsync:

.
disable = no
# flags = IPv6
.

Создадим отдельного пользователя rsync без домашней директории и /sbin/nologin. Да, я люблю вместо общего nobody для важных задач создавать отдельных пользователей. Никогда не знаешь наперед, когда придется анализировать, что и где глючит.

Редактируем (создаем) минимальный конфиг rsync на сервере 1.1.1.1:

service xinetd restart

netstat -lnpt | grep 873
tcp 0 0 . 873 . * LISTEN 16269/xinetd

Ок, xinetd слушает порт rsync и при запросе запустит его.

На сервере 2.2.2.2 (с которого будем коннектится) сгенерируем сертификат для доступа без пароля:

/.ssh/id_rsa -q -P «» -b 4096

  • -q — silense
  • -f — имя файла ключа
  • -P «» — пустой пароль
  • -b 4096 — размер ключа, бит

Просмотрим публичный ключ, который надо будет скопировать на 1.1.1.1, куда будем впоследствии подсоединяться:

На сервере 1.1.1.1 (откуда будем копировать файлы).

Скопируем этот ключ на сервер 1.1.1.1, на который будем логиниться, в директорию пользователя user1, под которым будем логинитсья, в файл

Если директории .ssh на 1.1.1.1 не существует, создадим ее:

/.ssh/authorized_keys
chmod 0644

/.ssh/authorized_keys копируем содержимое публичного ключа, созданного на сервере 2.2.2.2 (файл id_rsa.pub) и перезапускаем sshd:

# service sshd restart

Читайте также:  Qlik sense windows server

Все, мы готовы проверить соединение с 2.2.2.2 на 1.1.1.1 по ssh:

ssh -i /home/user2/.ssh/id_rsa -p 22 user1@1.1.1.1

Если соединение прошло, можно двигаться дальше. Если нет — надо обязательно понять, где проблема (firewall, ошибка copy/paste ключа, забыли restart sshd, что-то еще).

Запускаем rsync через ssh

Мы будем копировать файлы /data/* с сервера 1.1.1.1 на сервер 2.2.2.2 в папку /backup/.

Формат простой: rsync [опции] [откуда] [куда]

rsync -avz -e «ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null» —progress 1.1.1.1:/data/data.zip /backup/

rsync -avz -e «ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null» —progress user1@1.1.1.1:/data/* /backup/

rsync -avz -e «ssh -p 22» —progress user1@1.1.1.1:/data/* /backup/

-e «ssh . « — указываем, что хотим все передавать по ssh;
-p 22 — указываем порт, на котором работает ssh на сервере 1.1.1.1;
-a, —archive – архивный режим, включает рекурсивное копирование и сохранение прав и владельца;
-v — расширенный вывод;
-z — использовать компрессию данных;
user1 — локальный пользователь сервера 1.1.1.1, настроенный на логин по ssh по ключу.

Естественно, пользователь user1 должен иметь права доступа в /data/.

Вот и все. После копирования проверим, создался ли файл на сервере 2.2.2.2:

Windows rsync with ssh

Portable Rsync With SSH For Windows

Based on github: fdcastel/cygrsync, a portable distribution of rsync with SSH for Windows. Uses the binaries from cygwin. Runs without cygwin installed.

When run from the bin/ directory, the rsync and ssh commands believe that they are running from /bin/ and that the root is their parent folder.

To access Windows paths, you must specify them in cygwin format without the /cygdrive path prefix (as configured in etc/fstab ). E.g., /c/my-folder points to C:\my-folder .

The exception is the home folder since etc/nsswitch.conf tells them to use your Windows home as the home directory.

By default, the command will try to use the keys defined in your «$\.ssh» (using your Windows home). The keys in here must be in Linux format (with LF line endings), not Windows format (with CRLF line endings).

The ssh binary that comes with this distribution cannot read keys with Windows line endings and will throw an invalid format error while trying to load the key. The OpenSSH version that comes preinstalled on Windows 10, on the other hand, can read keys with Linux line endings properly. So as long as your keys are written out with Linux line endings (e.g., generated from Windows Subsystem for Linux, etc.), then they will work under both Windows and this emulated cygwin rsync.

Note: Node.js always writes out files with LF line endings, even on Windows. So if you’re generating your keys from Node.js, you should be fine with the default behaviour.

Include node_modules/@small-tech/portable-rsync-with-ssh-for-windows in your resources.

This was created by following the instructions on github: fdcastel/cygrsync to create an up-to-date distribution of rsync and SSH from cygwin.

The same set of libraries (some of which were newer versions) were copied from the resulting files.

The current build has the following versions of the commands:

Version 3.2.0 dev (protocol version 31)

  • OpenSSH Version 8.3p1
  • OpenSSL Version 1.1.1f (31 March, 2020)

(In our testing, this is compatible with what is currently installed on our Linux servers: rsync 3.1.3 protocol version 31 and OpenSSH 8.2p1, OpenSSL 1.1.1f 31 March, 2020.)

About

Based on github: fdcastel/cygrsync, a portable distribution of rsync with SSH for Windows. Uses the binaries from cygwin. Runs without cygwin installed.

eCommerce и не только

AddThis Smart Layers

воскресенье, 24 января 2016 г.

Настройка репликации rsync по SSH без пароля

При работе с кластерами часто необходимо делать синхронизацию файлов (репликацию) при помощи команды rsync.
Другим примером использования данной команды будет перенос файлов с одного сервера на другой при апгрейде или для создания резервных копий данных.

Читайте также:  Как сделать рекавери для windows 10

Если при одноразовом использовании rsync чаще всего вопросов нет, то при автоматизации процесса репликации возникает проблема авторизации.
Ведь при репликации файлов между серверами при помощи команды rsync мы устанавливаем соединение с удаленным сервером и каждый раз будет затребован пароль для идентификации пользователя.
Нам же нужно автоматизировать выполнение команды так, чтобы пароль не требовался, но при этом ни в коем случае нельзя нигде хранить пароль в текстовом виде.

В общем виде команда для репликации файлов будет выглядеть так:

При помощи команды выше мы синхронизируем содержимое пользовательской директории /home/user/ на локальном сервере в идентичную директорию на сервере 192.168.0.2, при этом мы должны идентифицироваться под пользователем [email protected].0.2.

В стандартном случае, после запуска этой команды система попросит авторизоваться:
И до тех пор, пока пароль не будет указан команда не будет выполнена.

Для того, чтобы можно было получать доступ к удаленному серверу без авторизации нам нужно сделать несколько довольно простых шагов.

1. Генерация пары ключей при помощи ssh-keygen

При этом система запросит ввести ключевую фразу (пароль) либо оставить ее пустой

Данный мануал не призван объяснять основы и принципы сетевой безопасности, поэтому напишу лишь буквально в двух словах об этом.
На самом деле, метод идентификации при помощи пары ключей является более надеждым чем идентификация при помощи обычного пароля лишь в том случае, когда используется двухуровневая авторизация. Т.е. недостаточно иметь пару ключей, нужно еще знать пароль (ту самую ключевую фразу). Если же пароля нет, то теоретически злоумышленник запросто получает доступ к удаленному серверу.

Но, как я уже написал, это тема для отдельной статьи.
Здесь же, для того чтобы упросить задачу мы намеренно создаем пару ключей без пароля.

2. Копирование публичного ключа на удаленный сервер

При этом система попросит ввести пароль пользователя [email protected]

Примечание: Команда ssh-copy-id по умолчанию пытается подключаться к удаленному серверу по порту 22. Если же этот порт закрыт и доступ по ssh возможен по другому порту, например 2020, необходимо указывать это явно.

После того как публичная часть ключа была успешно скопированна на удаленный сервер попытаемся подключиться к нему еще раз.

Либо, в случае когда используется нестандартный порт, например 2020:

На этот раз пароль запрошен не будет.

2. Синхронизация файлов при помощи rsync

Еще раз запустим синхронизацию при помощи rsync

В случае с нестандартным портом команда будет выглядеть следующим образом:

Если все пункты выше были сделаны корректно, команда должна отработать не задавая дополнительных вопросов.

И последнее примечание: для корректной работы rsync на обоих серверах должна быть установлена идентичная версия сервиса openSSH.
Проверить это можно при помощи команды

В моем случае в ответ я получаю на обоих серверах

How to Transfer Files with Rsync over SSH

PHP Code

  1. Home
  2. Web Servers
  3. How to Transfer Files with Rsync over SSH

Rsync stands for “Remote Sync.” The rsync command lets you transfer and synchronize data between different machines and directories. Using the Secure Shell (SSH) protocol, you can copy your files securely to another location.

The rsync tool has many benefits when compared to other methods for copying files. It uses both compression and decompression while sending and receiving files. The tool only transfers new or updated files saving on bandwidth and bringing faster transfer times.

Follow this guide to learn how to use rsync over SSH to transfer or copy files.

  • User with sudo or root privileges
  • SSH access to a server via command line/terminal window
  • Rsync installed on the local and destination machine

Verify Rsync Installation

Most recent Linux distributions have rsync by default. To verify your system has rsync installed, run the installation command.

For Debian and Ubuntu machines, use apt-get :

If rsync is already installed, the output shows the current version of the tool.

Читайте также:  Rk x frnbdfwbb windows 10 pro

On RPM-based machines, such as CentOS, use:

Transfer Files with Rsync over SSH

Before you can start transferring files and directories with rsync over SSH, make sure you can use SSH to connect to a remote server. Once verified, you can begin backing up your data. Ensure your destination system has sufficient storage space.

The syntax for copying files to a remote server over SSH with the rsync command is:

Note: You need to enter your password every time you run the rsync command. To avoid doing so, you can set SSH key-based authentication. You can omit the username from the command if you want to use the currently logged in user.

rsync Command Examples

Follow the rest of the guide to see the examples of the most common rsync use cases.

Transfer a Specific File with Rsync

To transfer a single file to a remote machine, enter the full path of the source file. For example:

Make sure you use the quotes for files that contain spaces in the name. For example:

Transfer Contents of a Directory with Rsync

There are a few options when syncing directory contents with rsync over SSH.
To transfer all files from a source directory to target on a remote host, enter:

The asterisk (*) instructs the tool to include all files in the source directory. Subdirectories are not transferred.

The output shows the directories that rsync skipped during the transfer.

To include all subdirectories from the source directory, use the -r (recursive) or -a (archive) option. The -a flag is what we recommend. This option syncs recursively and keeps all permission and file settings. This time do not use the asterisk in the source path.

When you run the command in this format, rsync transfers all files and subdirectories from the source directory to the target location. From our example above, the test folder will have the contents of the Dir1 source when the transfer completes.

To omit files from being copied check out our guide on how to exclude files and directories in data transfer using rsync command.

Note: The trailing slash in the source path plays an important role. If you enter a source directory path without the slash at the end, rsync first transfers the source directory and then its contents. To demonstrate, we will remove the trailing slash from the example above:

When we open the test directory, it contains the Dir1 directory and then the rest of the files in Dir1.

Check Rsync File Transfer Progress

To check the status of rsync transfers, use the -P option. This option displays the transfer times, as well as the names of the files and directories that are synced.

If there is an issue with your connection and the sync is interrupted, -P resumes your transfers.

Run the command in this format to sync recursively and check the status of the transfer:

If you rerun the same command when there haven’t been any changes in the source directory, the transfer does not occur. The reason is that rsync only transfers modifications in files and new files. In this case, the output shows only the following line:

When there is a change even in one source file, rsync detects it and syncs it with the target.

We made a change in one file and re-ran the same command:

The output shows the source sample2 file was transferred since rsync detected that we modified the file.

With the Linux commands in this guide, you should be able to transfer files with rsync over SSH. We listed the most common options with rsync so you can successfully backup your data to a remote location.

Оцените статью