Rsync error chroot failed

I have set up a rsync server -> /etc/rsyncd.conf max connection = 5 log file = /var/log/rsync.log [web] path = /srv/www/html read only = false list = yes hosts allow = 127.0.0.1 ui...

I have set up a rsync server -> /etc/rsyncd.conf

max connection = 5  
log file = /var/log/rsync.log  
[web]  
path = /srv/www/html  
read only = false  
list = yes  
hosts allow = 127.0.0.1  
uid = nobody  
gid = nobody  

[root@localhost www]# ls -l /srv/www/html/  
-rwxrwxrwx. 1 amit amit 8 Apr 28 10:37 index.html  

If I do

$rsync 127.0.0.1::
$web  

then it correctly shows the module name
but if I do

$rsync 127.0.0.1::web  
@ERROR: chroot failed  
rsync error: error starting client-server protocol (code 5) at main.c(1503) [receiver=3.0.6]

I dont know why? I am testing working of rsync first on localhost as it failed rsync remotely.

matthias_h's user avatar

matthias_h

11.3k9 gold badges21 silver badges40 bronze badges

asked Apr 28, 2013 at 20:31

script_kiddie's user avatar

script_kiddiescript_kiddie

1,1574 gold badges11 silver badges24 bronze badges

1

The solution is
In /etc/rsyncd.conf on server add

use chroot = false

I have no clue why its true by default. Got to the solution by luck while browsing rsync documentation. Hope this saves time for others.
Cheers

answered Apr 28, 2013 at 20:59

script_kiddie's user avatar

script_kiddiescript_kiddie

1,1574 gold badges11 silver badges24 bronze badges

1

I faced the same issue and noticed the path I was giving in the rsyncd.conf at the server end was wrong.
Actual path was
path=/usr/share/tomcat/webapps/folder
but I was giving
path=/usr/share/tomcat6/webapps/folder
when I corrected the path is worked.So ensure that your path is correct has right ownership and permissions.

answered May 18, 2020 at 11:05

aastha's user avatar

This is likely an SELinux issue, it needs to know that the folder can be used by the rsync daemon. Let’s consider an example, to rsync the following folder: /home/myuser/ftp

The following commands need to be run to set the correct SELinux context:

semanage fcontext -a -t rsync_data_t '/home/myuser(/.*)?'
restorecon -Rv '/home/myuser'
setsebool -P rsync_client on

Strangely enough, I noticed the parent folder must be labelled, hence why the labelling is done on /home/myuser instead of /home/myuser/ftp. Restricting to the ftp subfolder is simply done in the rsync daemon configuration.

You can check the SELinux labelling by running:

ls -Z /home/myuser

An interesting article about why combining chroot and SELinux is a good idea: http://blog.siphos.be/2012/04/why-both-chroot-and-selinux/

answered May 5, 2020 at 15:17

Paul Podgorsek's user avatar

Paul PodgorsekPaul Podgorsek

2,3793 gold badges19 silver badges22 bronze badges

I have set up a rsync server -> /etc/rsyncd.conf

max connection = 5  
log file = /var/log/rsync.log  
[web]  
path = /srv/www/html  
read only = false  
list = yes  
hosts allow = 127.0.0.1  
uid = nobody  
gid = nobody  

[root@localhost www]# ls -l /srv/www/html/  
-rwxrwxrwx. 1 amit amit 8 Apr 28 10:37 index.html  

If I do

$rsync 127.0.0.1::
$web  

then it correctly shows the module name
but if I do

$rsync 127.0.0.1::web  
@ERROR: chroot failed  
rsync error: error starting client-server protocol (code 5) at main.c(1503) [receiver=3.0.6]

I dont know why? I am testing working of rsync first on localhost as it failed rsync remotely.

matthias_h's user avatar

matthias_h

11.3k9 gold badges21 silver badges40 bronze badges

asked Apr 28, 2013 at 20:31

script_kiddie's user avatar

script_kiddiescript_kiddie

1,1574 gold badges11 silver badges24 bronze badges

1

The solution is
In /etc/rsyncd.conf on server add

use chroot = false

I have no clue why its true by default. Got to the solution by luck while browsing rsync documentation. Hope this saves time for others.
Cheers

answered Apr 28, 2013 at 20:59

script_kiddie's user avatar

script_kiddiescript_kiddie

1,1574 gold badges11 silver badges24 bronze badges

1

I faced the same issue and noticed the path I was giving in the rsyncd.conf at the server end was wrong.
Actual path was
path=/usr/share/tomcat/webapps/folder
but I was giving
path=/usr/share/tomcat6/webapps/folder
when I corrected the path is worked.So ensure that your path is correct has right ownership and permissions.

answered May 18, 2020 at 11:05

aastha's user avatar

This is likely an SELinux issue, it needs to know that the folder can be used by the rsync daemon. Let’s consider an example, to rsync the following folder: /home/myuser/ftp

The following commands need to be run to set the correct SELinux context:

semanage fcontext -a -t rsync_data_t '/home/myuser(/.*)?'
restorecon -Rv '/home/myuser'
setsebool -P rsync_client on

Strangely enough, I noticed the parent folder must be labelled, hence why the labelling is done on /home/myuser instead of /home/myuser/ftp. Restricting to the ftp subfolder is simply done in the rsync daemon configuration.

You can check the SELinux labelling by running:

ls -Z /home/myuser

An interesting article about why combining chroot and SELinux is a good idea: http://blog.siphos.be/2012/04/why-both-chroot-and-selinux/

answered May 5, 2020 at 15:17

Paul Podgorsek's user avatar

Paul PodgorsekPaul Podgorsek

2,3793 gold badges19 silver badges22 bronze badges

#1 2020-06-29 08:18:19

Fomalhaut
Member
Registered: 2020-06-29
Posts: 5

rsyncd chroot failed

I’m using 2 laptops, both of them running arch linux. When I try to transfer files from one to another with rsync, it failed.

journalctl -xe | grep «rsync» on server outputs:

rsync: [Receiver] chroot /home/***/shared failed: No such file or directory (2)

but this directory exists, with permission 777, and owner is nobody.

this is /etc/rsyncd.conf

uid = nobody
gid = nobody
use chroot = yes
max connections = 4
syslog facility = local5
pid file = /run/rsyncd.pid
address = 10.0.0.1

[shared]
	path = /home/***/shared
	comment = shared folder

when I disable «use chroot», the error is «chdir failed».

How can I fix it?
thanks.

I have searched on web but I found nothing.

Last edited by Fomalhaut (2020-06-29 08:19:03)

#2 2020-06-29 08:44:02

schard
Member
From: Hannover
Registered: 2016-05-06
Posts: 1,610
Website

Re: rsyncd chroot failed

Did you redact the original folder name here or is the directory name actually ‘***’?
In the latter case, you should consider renaming the folder, since the asterisk might cause troubles as it’s commonly being used as a globbing character.

The next thing would be to test, whether the user nobody can actually access the given folder.
If the specified path is a subdir of another user’s home directory, this is most likely not the case.

#3 2020-06-29 15:07:03

Fomalhaut
Member
Registered: 2020-06-29
Posts: 5

Re: rsyncd chroot failed

schard wrote:

Did you redact the original folder name here or is the directory name actually ‘***’?
In the latter case, you should consider renaming the folder, since the asterisk might cause troubles as it’s commonly being used as a globbing character.

The next thing would be to test, whether the user nobody can actually access the given folder.
If the specified path is a subdir of another user’s home directory, this is most likely not the case.

I tried another directory, but I got same error again. In this case, all ancestor directories are accessible.

#4 2020-06-29 15:23:51

schard
Member
From: Hannover
Registered: 2016-05-06
Posts: 1,610
Website

Re: rsyncd chroot failed

You cannot get the same error, if you changed the directory, since the path should subsequently have changed.
Post some actual information like full configuration and log files and directory permissions.

#5 2020-06-29 17:29:01

Fomalhaut
Member
Registered: 2020-06-29
Posts: 5

Re: rsyncd chroot failed

schard wrote:

You cannot get the same error, if you changed the directory, since the path should subsequently have changed.
Post some actual information like full configuration and log files and directory permissions.

full configuration had been posted above, except username.

journalctl -xe | grep «rsync»

6月 29 15:27:40 fomalhaut audit[1]: SERVICE_START pid=1 uid=0 auid=4294967295 ses=4294967295 subj==unconfined msg='unit=rsyncd comm="systemd" exe="/usr/lib/systemd/systemd" hostname=? addr=? terminal=? res=success'
6月 29 15:27:40 fomalhaut rsyncd[2620]: rsyncd version 3.2.1 starting, listening on port 873
6月 29 15:27:43 fomalhaut rsyncd[2623]: name lookup failed for 10.0.0.2: Name or service not known
6月 29 15:27:43 fomalhaut rsyncd[2623]: connect from UNKNOWN (10.0.0.2)
6月 29 15:27:43 fomalhaut rsyncd[2623]: rsync allowed access on module shared from UNKNOWN (10.0.0.2)
6月 29 15:27:43 fomalhaut rsyncd[2623]: rsync: [Receiver] chroot /home/fomalhaut/shared failed: No such file or directory (2)

Hi,

I have a Readynas NV+ v1 and have setup various backup jobs to the same rsync server. Each backups a subset of the NAS.

I don’t know exactly when or why it started but since some weeks I have big problems with these rsync backups. As explained below I found out that every second backup job fails with this error:
@ERROR: chroot failed
rsync error: error starting client-server protocol (code 5) at main.c(1534) [sender=3.0.9]

And it’s really strange, every 2nd job fails. So I SSHed into the box and tried the rsync command (which I got from «top») manually in the shell:
rsync -aAv —links -8 —delete —compress —port=873 .

ftpbackup-217075@rsync1.euserv.de

::ftpbackup-217075/ReadyNAS/MediaVault/Install

and what I twanted to backup is /c/Install, so I cd’ed into this directory and issued the command above. And the error occurs really alternating. Means once the command runs fine. Then I execute it a 2nd time from the shell history and it fails with the above error. the 3rd time it runs fine, the 4th time it fails with same error and so one.

I already tried modifying /etc/frontview/Shares.conf to not use chroot with «use chroot = no» and instead «fake super = yes» but with no luck. I also tried experimenting with the rsync command by setting timeouts or limiting connections to only 1 but with no luck so far.

Does anyone know what this bevaviour could be because also /var/log/rsync.log is not very helpful, there I see:
2012/09/08 21:03:07 [1379] rsyncd version 3.0.9 starting, listening on port 873
2012/09/30 14:32:11 [1390] rsyncd version 3.0.9 starting, listening on port 873
2012/10/05 14:09:10 [1390] rsync error: received SIGINT, SIGTERM, or SIGHUP (code 20) at rsync.c(551) [Receiver=3.0.9]
2012/10/05 14:18:04 [1744] rsyncd version 3.0.9 starting, listening on port 873
2013/02/28 13:47:05 [1417] rsyncd version 3.0.9 starting, listening on port 873
2013/05/18 12:58:22 [1417] rsync error: received SIGINT, SIGTERM, or SIGHUP (code 20) at rsync.c(551) [Receiver=3.0.9]

As you can see here from the log too, once it works once not. For example the job with the pid 1379 worked, but 1390 had the error, 1744 worked, 1417 had the error and so on.

Also rebooting did not help, I’m still getting the same errors. I’m really out of ideas. I really hope anyone can help. I’m also not sure if this started with the RAIDiator update to 4.1.13. But I don’t know where to get an old version to test and if it’s safe to downgrade.

Thanks for any help on this.

Содержание

  1. Arch Linux
  2. #1 2020-06-29 08:18:19
  3. rsyncd chroot failed
  4. #2 2020-06-29 08:44:02
  5. Re: rsyncd chroot failed
  6. #3 2020-06-29 15:07:03
  7. Re: rsyncd chroot failed
  8. #4 2020-06-29 15:23:51
  9. Re: rsyncd chroot failed
  10. #5 2020-06-29 17:29:01
  11. Re: rsyncd chroot failed
  12. every 2nd rsync backup fails with @ERROR: chroot failed
  13. Troubleshooting rsync with Readynas, Azure and Centos
  14. rsync: getaddrinfo: myserver.northeurope.cloudapp.azure.com 873: Name or service not known
  15. rsync: failed to set times on “.” (in frontbut): Operation not permitted (1)
  16. ERROR: The remote path must start with a module name not a /
  17. @ERROR: Unknown module ‘mnt’
  18. @ERROR: chroot failed
  19. @ERROR: chdir failed
  20. Русские Блоги
  21. Linux rsync настройки
  22. Linux rsync настройки
  23. Ошибка 1:
  24. Ошибка 2:
  25. Ошибка 3:
  26. Ошибка 4:
  27. Ошибка 5:
  28. Ошибка 6:
  29. Ошибка семь:

Arch Linux

You are not logged in.

#1 2020-06-29 08:18:19

rsyncd chroot failed

I’m using 2 laptops, both of them running arch linux. When I try to transfer files from one to another with rsync, it failed.

journalctl -xe | grep «rsync» on server outputs:

but this directory exists, with permission 777, and owner is nobody.

this is /etc/rsyncd.conf

when I disable «use chroot», the error is «chdir failed».

How can I fix it?
thanks.

I have searched on web but I found nothing.

Last edited by Fomalhaut (2020-06-29 08:19:03)

#2 2020-06-29 08:44:02

Re: rsyncd chroot failed

Did you redact the original folder name here or is the directory name actually ‘***’?
In the latter case, you should consider renaming the folder, since the asterisk might cause troubles as it’s commonly being used as a globbing character.

The next thing would be to test, whether the user nobody can actually access the given folder.
If the specified path is a subdir of another user’s home directory, this is most likely not the case.

Солідарність з Україною

#3 2020-06-29 15:07:03

Re: rsyncd chroot failed

Did you redact the original folder name here or is the directory name actually ‘***’?
In the latter case, you should consider renaming the folder, since the asterisk might cause troubles as it’s commonly being used as a globbing character.

The next thing would be to test, whether the user nobody can actually access the given folder.
If the specified path is a subdir of another user’s home directory, this is most likely not the case.

I tried another directory, but I got same error again. In this case, all ancestor directories are accessible.

#4 2020-06-29 15:23:51

Re: rsyncd chroot failed

You cannot get the same error, if you changed the directory, since the path should subsequently have changed.
Post some actual information like full configuration and log files and directory permissions.

Солідарність з Україною

#5 2020-06-29 17:29:01

Re: rsyncd chroot failed

You cannot get the same error, if you changed the directory, since the path should subsequently have changed.
Post some actual information like full configuration and log files and directory permissions.

full configuration had been posted above, except username.

Источник

every 2nd rsync backup fails with @ERROR: chroot failed

I have a Readynas NV+ v1 and have setup various backup jobs to the same rsync server. Each backups a subset of the NAS.

I don’t know exactly when or why it started but since some weeks I have big problems with these rsync backups. As explained below I found out that every second backup job fails with this error:
@ERROR: chroot failed
rsync error: error starting client-server protocol (code 5) at main.c(1534) [sender=3.0.9]

And it’s really strange, every 2nd job fails. So I SSHed into the box and tried the rsync command (which I got from «top») manually in the shell:
rsync -aAv —links -8 —delete —compress —port=873 . ftpbackup-217075@rsync1.euserv.de ::ftpbackup-217075/ReadyNAS/MediaVault/Install

and what I twanted to backup is /c/Install, so I cd’ed into this directory and issued the command above. And the error occurs really alternating. Means once the command runs fine. Then I execute it a 2nd time from the shell history and it fails with the above error. the 3rd time it runs fine, the 4th time it fails with same error and so one.

I already tried modifying /etc/frontview/Shares.conf to not use chroot with «use chroot = no» and instead «fake super = yes» but with no luck. I also tried experimenting with the rsync command by setting timeouts or limiting connections to only 1 but with no luck so far.

Does anyone know what this bevaviour could be because also /var/log/rsync.log is not very helpful, there I see:
2012/09/08 21:03:07 [1379] rsyncd version 3.0.9 starting, listening on port 873
2012/09/30 14:32:11 [1390] rsyncd version 3.0.9 starting, listening on port 873
2012/10/05 14:09:10 [1390] rsync error: received SIGINT, SIGTERM, or SIGHUP (code 20) at rsync.c(551) [Receiver=3.0.9]
2012/10/05 14:18:04 [1744] rsyncd version 3.0.9 starting, listening on port 873
2013/02/28 13:47:05 [1417] rsyncd version 3.0.9 starting, listening on port 873
2013/05/18 12:58:22 [1417] rsync error: received SIGINT, SIGTERM, or SIGHUP (code 20) at rsync.c(551) [Receiver=3.0.9]

As you can see here from the log too, once it works once not. For example the job with the pid 1379 worked, but 1390 had the error, 1744 worked, 1417 had the error and so on.

Also rebooting did not help, I’m still getting the same errors. I’m really out of ideas. I really hope anyone can help. I’m also not sure if this started with the RAIDiator update to 4.1.13. But I don’t know where to get an old version to test and if it’s safe to downgrade.

Источник

Troubleshooting rsync with Readynas, Azure and Centos

Years ago i bought a couple of Netgear Readynas devices. A duo, and then subsequently a duo v2. They’re pretty basic, but offered good squeezebox support and a cheap way of me storing TB of data in a RAID config.

Both of the Readynas devices support backup operations to send their data on a scheduled basis. I’d normally opt for the simplicity of CIFS/Samba, but my internet provider has decided to block those ports and the Readynas devices don’t allow you to use a non-standard port. Thusly the only other way to get the job done is to use rsync.

My desired location for the data backup is in Azure (naturally!). Ideally in Azure files as my data will be the most accessible to me over an smb share in the same way that i’ve always accessed my ReadyNas devices.

Here’s a run down of a bunch of the errors i received when doing this and how to get around them.

rsync: getaddrinfo: myserver.northeurope.cloudapp.azure.com 873: Name or service not known

It turned out that my rsync daemon wasn’t listening correctly.

The quick command to get it running is

rsync: failed to set times on “.” (in frontbut): Operation not permitted (1)

At first i thought this problem was because of the way i was mounting Azure files and that it’s filesystem didn’t support it. Most of the solutions on the web tell you to use the -O flag to omit updating directory times.

However the solution was that the username my Readynas was using was not the owner of the directory.

This statement changes the ownership (recursively) of the directory to user1. This should match the username you are using in the Readynas and the rsyncd.conf file

ERROR: The remote path must start with a module name not a /

Pretty easy one here. The path must only represent the module defined in the rsyncd.conf file – not the directory path.

@ERROR: Unknown module ‘mnt’

I was having an issue whereby the config file i was using wasn’t being picked up by rsync (typo).
I was editing /etc/rsync.conf when it should have been /etc/rsyncd.conf.
Inside this configuration files are various module definitions (specifying the path etc), the module must be used.

@ERROR: chroot failed

In your rsyncd.conf file make sure that chroot = false

@ERROR: chdir failed

Ensure that the directory has the correct permissions allocated.

Источник

Русские Блоги

Linux rsync настройки

Linux rsync настройки

Наклейки могут возникнуть при использовании RSYNC в использовании.

Ошибка 1:

@ERROR: auth failed on module xxxxx
rsync: connection unexpectedly closed (90 bytes read so far)
rsync error: error in rsync protocol data stream (code 12) at io.c(150)
Решение: это связано с тем, что пароль устанавливается неправильно и не может быть успешно войти в систему. Проверьте rsync.pwd и посмотрите, соответствуют ли клиент и сервер. Это также имеет место без запуска службы RSYNC на сервере.

Ошибка 2:

Ошибка 3:

password file must not be other-accessible
continuing without password file
Password:
Решение: это связано с тем, что разрешения rsyncd.pwd rsyncd.sec неверны, и это должно быть установлено на 600. Такие как: chmod 600 rsyncd.pwd

Ошибка 4:

@ERROR: chroot failed
rsync: connection unexpectedly closed (75 bytes read so far)
rsync error: error in rsync protocol data stream (code 12) at io.c(150)
Решение: это потому, что вы не существуете в пути пути, который вы устанавливаете в rsync.conf, вам необходимо создать новый каталог для запуска синхронизации.

Ошибка 5:

rsync: failed to connect to 218.107.243.2: No route to host (113)
rsync error: error in socket IO (code 10) at clientserver.c(104) [receiver=2.6.9]
Решение: у другой стороны нет брандмауэра, брандмауэр заблокирован, а в сети есть блок брандмауэра. Это возможно. Закрытие брандмауэра фактически открывает 873 порт TCP UDP.

Ошибка 6:

Сообщение об ошибке: на сервере указано файл пароля как /etc/rsyncd.secrets через файл Secrets. Клиенту не разрешается нажимать или вытащить файлы из сегмента сервера.

Решение: файл пароля с открытым текстом, установленная в файле Secrets, работает только тогда, когда пользователи Auth определяются в этом модуле.

Ошибка семь:

[[email protected] /mnt]# rsync -avzP —password-file=/etc/rsyncd.pwd rsync 10.10.10.100::rsync

@ERROR: invalid gid nobody
rsync error: error starting client-server protocol (code 5) at main.c(1503) [sender=3.0.6]

Решение: общая заданная GID — это никто, но в подсказке ошибки четко указывается, что GID = никто не является незаконным. После изменения никого на корни проблема решена.

(Что касается того, можно ли его изменить на другие гневки, мои экспериментальные результаты здесь не увенчались успехом. Добавьте новый GID = hxtc в группу и Passwd в каталоге Target Poard/ETC. В то же время пароль, в то же время, UID , Пользователи GID и Auth в модуле RSYNCD.Conf на стороне сервера установлены на HXTC, и он все еще не может быть успешным.)

Прежде чем продолжить. Сущность

1. Введение в RSYNC

RSYNC (удаленная синхронизация) — это инструмент дистанционного синхронизации данных, который может быстро синхронизировать файлы между несколькими хостами через LAN/WAN или использовать различный каталог на локальном жестком диске с RSYNC.

RSYNC -это инструмент для замены RCP. RSYNC использует SO -накаленный «алгоритм RSYNC» для синхронизации файлов между локальными и длинными хостами. Передача, поэтому скорость довольно быстрая. Вы можете ссылаться наHow Rsync Works A Practical OverviewДалее понять операционный механизм RSYNC.

RSYNC поддерживает большинство систем UNIX, как Linux, Solaris или BSD прошли хорошие тесты. Кроме того, он также имеет соответствующую версию на платформе Windows, а более известными являются CWRSYNC и SYNC2NAS.

Первоначальным автором RSYNC являются Эндрю Тридгелл и Пол Макеррас.http://rsync.samba.orgподдерживать.

Основные характеристики RSYNC следующие:

1. Вы можете сохранить все дерево каталогов и файловую систему;

2. Он может легко поддерживать авторитет, время, жесткие и жесткие ссылки исходного файла;

3. Он может быть установлен без особых разрешений;

4. Оптимизированный процесс, высокая эффективность передачи файлов;

5. Вы можете использовать RCP, SSH и другие методы для передачи файлов. Конечно

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

При использовании RSYNC для удаленной синхронизации можно использовать два метода: Remote Shell (SSH рекомендуется, проверка пользователя отвечает за SSH) и C/S (то есть клиент подключает сервер удаленного RSYNC, и проверка пользователя отвечает за сервер RSYNC).

Независимо от локального каталога синхронизации или данных удаленной синхронизации, все файлы будут скопированы один раз во время выполнения, и при запуске будут скопированы только изменяемые файлы (для новых файлов) или файлов (для исходных файлов).

RSYNC не имеет преимущества скорости при первой копии, и скорость не так хороша, как TAR. Поэтому, когда количество данных велико, вы можете рассмотреть возможность использования TAR для первой копии, а затем использовать RSYNC для синхронизации данных.

Во -вторых, системная среда

Системная платформа:CentOS release 6.3 (Final)

Rsync версия:rsync-3.0.9-2.el6.rfx.x86_64.rpm

Rsync client:TS-CLIENT (172.16.1.136)

3. Установите сервис RSYNC на стороне сервера

3.1. Проверьте, был ли RSYNC установлен

# rpm -qa|grep rsync

Если он установлен, используйте команду RPM -E, чтобы удалить ее.

3.2. Скачать пакет RPM

3.3. Установите rsync

# rpm -ivh rsync-3.0.9-2.el6.rfx.x86_64.rpm

В -четвертых, настройте сервис RSYNC

4.1. Шаги настройки сервера RSYNC

4.2. Запустите сервис RSYNC с Xinetd

Centos запускает услуги RSYNC от Xinetd по умолчанию. Файл конфигурации Xinetd RSYNC
В /etc/xinetd.d/rsync. Чтобы настроить службу RSYNC, работающую с Xinetd, необходимо выполнить следующие команды:

Администраторы могут изменить файлы конфигурации /etc/xinetd.d/rsync для подходящих для вас. Например, вы можете изменить строку конфигурации

Добавьте параметры сервиса RSYNC позже.

4.3. Запустите сервис RSYNC независимо

Самый простой способ самостоятельного запуска службы RSYNC — это выполнить следующие команды:

Вы можете написать вышеуказанные команды в /етк /RC.Local File для службы RSYNC при запуске сервера каждый раз. Конечно, вы также можете написать скрипт для автоматического запуска службы RYSNC при загрузке.

4.4. Файл конфигурации rsyncd.conf

Оба метода работы Service Service должны настраивать rsyncd.conf, что аналогично основному файлу конфигурации Samba.
Настройте файл rsyncd.conf по умолчанию в каталоге /etc. Чтобы поместить все файлы, связанные с службой RSYNC в отдельном каталоге, могут быть выполнены следующие команды:

Файл конфигурации rsyncd.conf состоит из глобальной конфигурации и нескольких конфигурации модулей. Синтаксис файла конфигурации:

Глобальный параметр

Все строки конфигурации за пределами [модуля] в файле являются глобальными параметрами. Конечно, параметры модуля также могут быть определены в глобальном параметре. В настоящее время значение параметра — значение по умолчанию всех модулей.

параметр иллюстрировать По умолчанию
address При запуске самостоятельно IP -адрес, используемый для назначенного сервера. Этот параметр будет игнорироваться Xinetd при запуске, а параметры -ddress в командной строке будут заменены. Весь локальный IP
port Укажите номер порта, прослушивая процесс RSYNC Guardian. Этот параметр будет игнорироваться Xinetd при запуске, а опция порта в командной строке будет заменена. 873
motd file Укажите файл сообщения, содержание файла отображается клиенту, когда клиент подключает сервер. никто
pid file Процесс опекуна RSYNC записывает свой PID в указанный файл. никто
log file Укажите файл журнала процесса RSYNC Guardian, не отправляя журнал в Syslog. никто
syslog facility Укажите уровень сообщения, когда RSYNC отправляет сообщение журнала в Syslog. daemon
socket options Укажите пользовательские параметры TCP. никто

Параметр модуля

Параметры модуля в основном используются для определения того, какой каталог сервера RSYNC синхронизирован. Формат модуля должен быть [модуль]. Это имя является именем, которое можно увидеть на клиенте RSYNC, аналогично общему имени, предоставленному сервером Samba. Фактические данные синхронизации сервера указываются путем. Вы можете указать несколько модулей в соответствии с вашими собственными потребностями. Следующие параметры могут быть определены в модуле:

A. Основные параметры модуля

параметр иллюстрировать По умолчанию
path Укажите текущий путь синхронизации модуля на сервере RSYNC, этот параметр должен быть указан. никто
comment Укажите описание для модуля, который отображается для клиента, когда модуль подключен к списку модуля. никто

b. Параметры управления модулем

параметр иллюстрировать По умолчанию
use chroot Если это правда, первая хрота в каталог, указанный Chroot до передачи файла передачи. Причиной этого является достижение дополнительной защиты, но недостаток в том, что корневое разрешение требуется, и файл каталога указывал на направление соединения внешнего символа пути пути. true
uid Укажите модуль для передачи файлов с указанным UID. nobody
gid Укажите модуль для передачи файлов в указанный GID. nobody
max connections Укажите максимальное одновременное число модуля для защиты сервера, и запрос подключения, который превышает предел, будет протестирован, а затем опробован. 0 (без ограничений)
lock file Укажите файлы блокировки, которые поддерживают параметры Max Connections. /var/run/rsyncd.lock
list Укажите, должен ли модуль быть указан, когда запрос клиента перечисляет список модулей, который можно использовать. Если опция установлен на False, вы можете создать скрытый модуль. true
read only Укажите, разрешено ли клиенту загружать файлы. Если это правда, ему не разрешено загружать; если он ложный и серверный каталог имеет разрешения для чтения и записи, его разрешают загружать. true
write only Укажите, разрешено ли клиент загружать файл. Если это правда, загрузка не разрешена; если он неверно, а серверный каталог также имеет разрешения на чтение, это разрешено загружать. false
ignore errors Укажите, работает ли операция удаления на сервере RSYNC, чтобы игнорировать ошибку ввода/вывода. Вообще говоря, RSYNC пропустит операцию –lelete, когда возникает ошибка ввода/вывода, чтобы предотвратить серьезные проблемы, вызванные отсутствием временных ресурсов или других ошибок ввода -вывода. true
ignore nonreadable Укажите файлы, которые сервер RYSNC полностью игнорирует этих пользователей без доступа. Это имеет значение для некоторых файлов, которые не должны быть получены в каталоге, которые должны быть резервными. false
timeout Эта опция может охватить тайм -аут IP, указанный клиентом. В результате сервер RSYNC не будет ждать вечно клиента. Для анонимного сервера RSYNC идеальное число составляет 600 (устройство — секунд). 0 (неограниченный)
dont compress Используется для указания файлов, которые не сжимают обработку перед передачей. Эта опция может определить некоторые параметры команды, которые не позволяют клиентам использовать модуль. Полное имя опции должно использоваться вместо аббревиатуры. Когда возникает определенная опция, сервер сообщит об сообщении об ошибке и выходе. Например, чтобы предотвратить сжатие, это должно быть: «Не сжимайте = *». *.gz *.tgz *.zip *.z *.rpm *.deb *.iso *.bz2 *.tbz

c. Параметры проверки файла модуля

параметр иллюстрировать По умолчанию
exclude Укажите несколько файлов или каталога (относительных путей), разделенных пространствами, и добавьте его в список Exclude. Это эквивалентно использованию -clude для указания режима в команде клиента. нулевой
exclude from Укажите имя файла, определяемое правилом Exclude, и сервер считывает определение списка Excude из файла. нулевой
include Укажите несколько файлов или каталога (относительных путей), разделенных пространствами, и добавьте его в список включения. Это эквивалентно использованию -ингуляции для указания режима в команде клиента. нулевой
include from Укажите имя файла, определяемое включенными правилами, и сервер считывает определение списка включения из файла. нулевой
  • Модуль может указать только параметр exclude и параметр включения.
  • Комбинирование включает и исключать может определить комплекс исключать/включить правила.
  • Эти параметры эквивалентны соответствующим параметрам команды клиента RSYNC, и единственное отличие состоит в том, что они действуют на стороне сервера.
  • Для содержания того, как написать файл правил, обратитесь к немуhttp://www.howtocn.org/rsync:use_rsync。

D. Параметры аутентификации пользователя модуля

параметр иллюстрировать По умолчанию
auth users Укажите список списков пользователей, разделенных пространством или запятой, и только эти пользователи разрешают соединение с модулем. Пользователи здесь не имеют ничего общего с пользователями системы. Имена пользователей и пароли хранятся в файле, указанном параметром файла Secrets в чистом тексте. (Анонимный путь)
secrets file Укажите пароль сертификации RSYNC. Этот файл работает только тогда, когда пользователи Auth определяются. нулевой
strict modes Укажите разрешения файла или следить за файлом. Если это правда, файл пароля может быть доступен только пользователем сервера RSYNC. Любые другие пользователи не могут получить доступ к файлу. true
  • Разрешения пароля сертификации RSYNC должны составлять 600, в противном случае клиент не сможет подключиться к серверу.
  • Сертифицированный файл пароля RSYNC Укажите имя пользователя: пара паролей, формат:
  • Вообще говоря, лучше не превышать 8 символов. Если вы только настраиваете анонимный сервер RSYNC, вам не нужно устанавливать вышеуказанные параметры.

т. Модуле Параметры управления доступом

параметр иллюстрировать По умолчанию
hosts allow Используйте список хостов, который может подключаться к модулю. Хозяин, который не соответствует списку хостов, будет отклонен. *
hosts deny Используйте список хостов, который клиенты -хозяины не позволяют подключению подключения к модулю. нулевой

Определение списка хостов клиента может быть следующей формой:

  • Один IP -адрес. Например: 192.168.0.1
  • Весь сегмент сети. Например: 192.168.0.0/24, 192.168.0.0/255.255.255.0
  • Анализ одного имени хоста. Например: centos, centos.bsmart.cn
  • Все хосты в домене. Например:*. Bsmart.cn
  • «*» Означает все.
  • Несколько списков следует использовать в пространственных интервалах.

f. Параметр журнала модуля

параметр иллюстрировать По умолчанию
transfer logging Заставьте сервер RSYNC записать записи операции передачи в файл журнала передачи. false
log format Укажите поле файла журнала передачи. ”%o %h [%a] %m (%u) %f %l”

При настройке параметра «файла журнала» начало журнала будет добавлено «%t [%p]» в начале журнала.

  • % -Remote IP -адрес
  • %h -Remote Host Имя
  • %L -файл длины
  • %P -PID сеанса RSYNC
  • %O -Operation Тип: «Отправить» или «recv»
  • %f -файл имя
  • %P -модуля
  • %m -модуля имени
  • %T -Current Time
  • %u -сертифицированное имя пользователя (null, когда анонимно)
  • %B -количество байтов, которые фактическая передача
  • %C -во время отправки файлов запишите код проверки файла

5. Case Application RSYNC Server

5.1. Настройте сервис RSYNC на стороне сервера TS-DEV

A. Редактировать файл конфигурации

Дэвид: ASDF #Format Имя пользователя: пароль
Китай: JK #пользователь не требует, чтобы это система системы

c. для обеспечения безопасности пароля мы установили авторитет на 600

# chown root:root /etc/rsyncd/rsyncd.secrets

# chmod 600 /etc/rsyncd/rsyncd.secrets

ф. Посмотрите, встал ли порт 873

# netstat -an | grep 873

Если RSYNC начинается успешно, вы увидите, что порт 873 уже контролируется.

5.2. Конфигурация клиента

A. Установите rsync в клиенту

# yum -y install rsync

b. Покрытые данные через клиент RSYNC

Сцена первая:

# rsync -avzP [email protected]::davidhome /tmp/david/

Пароль: чтобы ввести пароль David здесь, он предоставляется стороной сервера. В предыдущем примере мы используем ASDF, и ввод пароля не отображается; после проигрыша
Примечание:Значение этой команды означает, что пользователь David входит в систему на сервере, а данные Davidhome синхронизируются с локальным каталогом/TMP/David/. Конечно, местный каталог может быть определен самостоятельно. Вы должны обратить внимание на его разрешения на написание.

иллюстрировать:
-А параметры, эквивалентные -rlptgod, -r является рекурсивным -l -это файл ссылки, что означает копирование файлов ссылок; -p указывает на то, что исходный авторитет файла сохраняется; -t поддерживает исходное время файла ;; -О, чтобы сохранить исходный владелец файла; -d эквивалентен блокированию файлов оборудования;
-Z сжатие во время передачи;
-P Прогресс передачи;
-В передача и другая информация и т. Д., Имейте немного связаны с -p, попробуйте самостоятельно. Вы можете прочитать документ;

Сцена вторая:
# rsync -avzP —delete [email protected]::davidhome /tmp/david/

На этот раз мы представили опцию –lelete, указывая на то, что данные на клиенте должны быть точно такими же, как на стороне сервера. Если на сервере есть файл в каталоге/TMP/David/David, удалите его. Конечная цель состоит в том, чтобы сохранить данные в каталоге/TMP/DAVID/DAVION; Вы удаляете все данные;

Сцена третья:
# rsync -avzP —delete —password-file=/tmp/rsync.password [email protected]::davidhome /tmp/david/

На этот раз мы добавили Option-Password-file = rsync.password. В настоящее время, когда мы войдем в синхронные данные сервера RSYNC с пользователями David, пароль будет читать файл /tmp/rsync.password. Содержание этого файла является только паролем для пользователей David. Мы должны сделать это следующим образом;

# touch /tmp/rsync.password
# chmod 600 /tmp/rsync.password
# echo «asdf»> /tmp/rsync.password
# rsync -avzP —delete —password-file=/tmp/rsync.password [email protected]::davidhome /tmp/david/

Примечание:Это не нуждается в пароле; на самом деле это более важно, потому что сервер все еще необходим с помощью задачи плана Crond;

5.3. Клиент RSYNC автоматически синхронизирует данные с сервером

Редактировать Crontab
# crontab -e
Добавьте следующий код:

Указывает следующие команды в 0:10 каждый день.

Шесть, анализ ошибок

rsync: opendir «.» (in xxxxxxx) failed: Permission denied (13)

1. Удалите все ограничения на rsync selinux:
# /usr/sbin/setsebool -P rsync_disable_trans 1
# service xinetd restart

2. Иногда запрещайте весь Selinux:
# vim /etc/selinux/config
Измените SELINUX = SELINUX = отключить
После сохранения выхода перезапустите машину.

До сих пор сервер RSYNC настроен.

7. Ссылка

Для использования команды RSYNC, пожалуйста, см.http://www.howtocn.org/rsync:use_rsync

Для получения подробных инструкций для службы RSYNC, пожалуйста, см.http://www.howtocn.org/rsync:use_rsync_server

David Camp

  • Технические обмены, пожалуйста, добавьте QQ Group:

Работа и техническое обслуживание системы. Обмен технологиями: 296513821

  • Бизнес -сотрудничество, пожалуйста, свяжитесь с автором QQ: 562866602
  • Мой WeChat: MCHINA_TANG
  • Напишите мне: [email protected]
  • Мой адрес: Цзянсу · Сучжоу

Мы всегда верим, что обмен — это добродетель |We Believe, Great People Share Knowledge.

Источник

Понравилась статья? Поделить с друзьями:
  • Rsync chdir failed error
  • Rsync error some files attrs were not transferred see previous errors code 23
  • Rsi launcher installer error
  • Rsg ms verify gta 5 как исправить
  • Rsync error sending incremental file list