GNU/Linux >> Linux の 問題 >  >> Ubuntu

Ubuntu20.04でLsyncdを使用してディレクトリを同期する方法

Lsyncdは、ローカルディレクトリをリモートサーバー上の別のディレクトリにミラーリングできるシンプルで軽量なツールです。これは、指定されたディレクトリの変更を数秒ごとに継続的に監視し、変更が加えられた場合はリモートサーバーに同期することで機能します。このツールは、安全な領域から安全でない領域にデータを同期するのに非常に便利です。

このチュートリアルでは、Lsyncdをインストールして使用し、ローカルディレクトリとリモートディレクトリを同期する方法を示します。

前提条件
  • Ubuntu20.04を実行しているサーバー。
  • ルートパスワードがサーバーに設定されています。
はじめに

開始する前に、システムのパッケージを最新バージョンに更新することをお勧めします。次のコマンドを使用して更新できます:

apt-get update -y
apt-get upgrade -y

すべてのパッケージが更新されたら、システムを再起動して変更を適用します。

Lsyncdをインストール

デフォルトでは、LsyncdパッケージはほとんどのLinuxオペレーティングシステムで利用できます。次のコマンドを実行するだけでインストールできます:

apt-get install lsyncd -y

Lsyncdをインストールしたら、次のコマンドを使用して、インストールされているLsyncdのバージョンを確認できます。

lsyncd --version

次の出力が得られるはずです:

Version: 2.2.3
ローカルディレクトリを同期するようにLsyncdを構成する

このセクションでは、/etc/ディレクトリをローカルシステムの/mnt/ディレクトリに同期するようにLsyncdを構成します。

まず、次のコマンドを使用してLsyncdのディレクトリを作成します。

mkdir /etc/lsyncd

次に、新しいLsyncd構成ファイルを作成し、同期するソースディレクトリと宛先ディレクトリを定義します。

nano /etc/lsyncd/lsyncd.conf.lua

次の行を追加します:

settings {
        logfile = "/var/log/lsyncd/lsyncd.log",
        statusFile = "/var/log/lsyncd/lsyncd.status",
   statusInterval = 20,
   nodaemon   = false
}

sync {
        default.rsync,
        source = "/etc/",
        target = "/mnt"
}

終了したら、ファイルを保存して閉じます。

systemctl start lsyncd
systemctl enable lsyncd

次のコマンドを使用して、Lsyncdサービスのステータスを確認することもできます。

systemctl status lsyncd

次の出力が表示されます。

? lsyncd.service - LSB: lsyncd daemon init script
     Loaded: loaded (/etc/init.d/lsyncd; generated)
     Active: active (running) since Fri 2020-05-01 03:31:20 UTC; 9s ago
       Docs: man:systemd-sysv-generator(8)
    Process: 36946 ExecStart=/etc/init.d/lsyncd start (code=exited, status=0/SUCCESS)
      Tasks: 2 (limit: 4620)
     Memory: 12.5M
     CGroup: /system.slice/lsyncd.service
             ??36921 /usr/bin/lsyncd -pidfile /var/run/lsyncd.pid /etc/lsyncd/lsyncd.conf.lua
             ??36952 /usr/bin/lsyncd -pidfile /var/run/lsyncd.pid /etc/lsyncd/lsyncd.conf.lua

May 01 03:31:20 ubuntu20 systemd[1]: lsyncd.service: Succeeded.
May 01 03:31:20 ubuntu20 systemd[1]: Stopped LSB: lsyncd daemon init script.
May 01 03:31:20 ubuntu20 systemd[1]: Starting LSB: lsyncd daemon init script...
May 01 03:31:20 ubuntu20 lsyncd[36946]:  * Starting synchronization daemon lsyncd
May 01 03:31:20 ubuntu20 lsyncd[36951]: 03:31:20 Normal: --- Startup, daemonizing ---
May 01 03:31:20 ubuntu20 lsyncd[36946]:    ...done.
May 01 03:31:20 ubuntu20 systemd[1]: Started LSB: lsyncd daemon init script.

以下に示すように、Lsyncdログファイルで詳細を確認できます。

tail -f /var/log/lsyncd/lsyncd.log

次の出力が表示されます。

/lsyncd/lsyncd.conf.lua
Fri May  1 03:30:57 2020 Normal: Finished a list after exitcode: 0
Fri May  1 03:31:20 2020 Normal: --- Startup, daemonizing ---
Fri May  1 03:31:20 2020 Normal: recursive startup rsync: /etc/ -> /mnt/
Fri May  1 03:31:20 2020 Normal: Startup of /etc/ -> /mnt/ finished.

次のコマンドを使用して、同期ステータスを確認することもできます。

tail -f /var/log/lsyncd/lsyncd.status

次のコマンドを使用して、/mntディレクトリの変更を確認できるはずです。

ls /mnt/

/etcディレクトリのすべてのファイルとディレクトリが/mntディレクトリに追加されていることを確認してください。

acpi                    dconf           hosts            logrotate.conf       newt                     rc2.d          subuid-
adduser.conf            debconf.conf    hosts.allow      logrotate.d          nginx                    rc3.d          sudoers
alternatives            debian_version  hosts.deny       lsb-release          nsswitch.conf            rc4.d          sudoers.d
apache2                 default         init             lsyncd               ntp.conf                 rc5.d          sysctl.conf
apparmor                deluser.conf    init.d           ltrace.conf          openal                   rc6.d          sysctl.d
apparmor.d              depmod.d        initramfs-tools  lvm                  opt                      rcS.d          systemd
apport                  dhcp            inputrc          machine-id           os-release               resolv.conf    terminfo
apt                     dnsmasq.d       insserv.conf.d   magic                overlayroot.conf         rmt            timezone
at.deny                 docker          iproute2         magic.mime           PackageKit               rpc            tmpfiles.d
bash.bashrc             dpkg            iscsi            mailcap              pam.conf                 rsyslog.conf   ubuntu-advantage
bash_completion         e2scrub.conf    issue            mailcap.order        pam.d                    rsyslog.d      ucf.conf
bash_completion.d       environment     issue.net        manpath.config       passwd                   screenrc       udev
bindresvport.blacklist  ethertypes      kernel           mdadm                passwd-                  securetty      ufw
binfmt.d                fonts           kernel-img.conf  mime.types           perl                     security       update-manager
byobu                   fstab           landscape        mke2fs.conf          php                      selinux        update-motd.d
ca-certificates         fuse.conf       ldap             modprobe.d           pki                      sensors3.conf  update-notifier
ca-certificates.conf    fwupd           ld.so.cache      modules              pm                       sensors.d      vdpau_wrapper.cfg
calendar                gai.conf        ld.so.conf       modules-load.d       polkit-1                 services       vim
console-setup           groff           ld.so.conf.d     mtab                 pollinate                shadow         vmware-tools
cron.d                  group           legal            multipath            popularity-contest.conf  shadow-        vtrgb
cron.daily              group-          letsencrypt      multipath.conf       profile                  shells         vulkan
cron.hourly             grub.d          libaudit.conf    mysql                profile.d                skel           wgetrc
cron.monthly            gshadow         libnl-3          nanorc               protocols                sos.conf       X11
crontab                 gshadow-        locale.alias     netplan              pulse                    ssh            xattr.conf
cron.weekly             gss             locale.gen       network              python3                  ssl            xdg
cryptsetup-initramfs    hdparm.conf     localtime        networkd-dispatcher  python3.8                subgid         zsh_command_not_found
crypttab                host.conf       logcheck         NetworkManager       rc0.d                    subgid-
dbus-1                  hostname        login.defs       networks             rc1.d                    subuid

リモートディレクトリを同期するようにLsyncdを構成する

このセクションでは、ローカルシステムの/etc/ディレクトリをリモートシステムの/opt/ディレクトリに同期するようにLsyncdを構成します。

開始する前に、ローカルシステムとリモートサーバーの間にSSHキーベースの認証を設定して、ローカルシステムがパスワードなしでリモートサーバーに接続できるようにする必要があります。

ローカルシステムで、次のコマンドを実行して公開鍵と秘密鍵を生成します。

ssh-keygen -t rsa

次の出力が表示されます。

Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa
Your public key has been saved in /root/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:c7fhjjhAamFjlk6OkKPhsphMnTZQFutWbr5FnQKSJjE [email protected]
The key's randomart image is:
+---[RSA 3072]----+
| E ..            |
|  ooo            |
| oo= +           |
|=.+ % o . .      |
|[email protected] oSo. o    |
|ooo=B o .o o o   |
|=o.... o    o    |
|+.    o .. o     |
|     .  ... .    |
+----[SHA256]-----+

上記のコマンドは、〜/.sshディレクトリ内に秘密鍵と公開鍵を生成します。

次に、公開鍵をリモートサーバーにコピーする必要があります。次のコマンドでコピーできます:

ssh-copy-id [email protected]

以下に示すように、リモートrootユーザーのパスワードを入力するように求められます。

[email protected]'s password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.

ユーザーが認証されると、公開鍵がリモートユーザーのauthorized_keysファイルに追加され、接続が閉じられます。

これで、パスワードを入力せずにリモートサーバーにログインできるようになります。

テストするには、SSH経由でリモートサーバーにログインしてみてください:

ssh [email protected]

すべてがうまくいけば、すぐにログインします。

次に、Lsyncd構成ファイルを編集し、rsyncsshとターゲットホスト変数を定義する必要があります。

nano /etc/lsyncd/lsyncd.conf.lua

以下に示すようにファイルを変更します:

settings {
        logfile = "/var/log/lsyncd/lsyncd.log",
        statusFile = "/var/log/lsyncd/lsyncd.status",
   statusInterval = 20,
   nodaemon   = false
}

sync {
        default.rsyncssh,
        source = "/etc/",
	host = "remote-server-ip",
        targetdir = "/opt"
}

終了したら、ファイルを保存して閉じます。次に、Lsyncdサービスを再起動して同期を開始します。

systemctl restart lsyncd

次のコマンドを使用して、同期のステータスを確認できます。

tail -f /var/log/lsyncd/lsyncd.log

次の出力が表示されます。

Fri May  1 04:32:05 2020 Normal: --- Startup, daemonizing ---
Fri May  1 04:32:05 2020 Normal: recursive startup rsync: /etc/ -> 45.58.38.21:/opt/
Fri May  1 04:32:06 2020 Normal: Startup of "/etc/" finished: 0

次のコマンドを使用して、リモートサーバーの/optディレクトリの変更を確認できるはずです。

ls /opt

/etcディレクトリのすべてのファイルとディレクトリがリモートサーバーの/optディレクトリに追加されていることを確認してください。

acpi                    dconf           hosts            logrotate.conf       newt                     rc2.d          subuid-
adduser.conf            debconf.conf    hosts.allow      logrotate.d          nginx                    rc3.d          sudoers
alternatives            debian_version  hosts.deny       lsb-release          nsswitch.conf            rc4.d          sudoers.d
apache2                 default         init             lsyncd               ntp.conf                 rc5.d          sysctl.conf
apparmor                deluser.conf    init.d           ltrace.conf          openal                   rc6.d          sysctl.d
apparmor.d              depmod.d        initramfs-tools  lvm                  opt                      rcS.d          systemd
apport                  dhcp            inputrc          machine-id           os-release               resolv.conf    terminfo
apt                     dnsmasq.d       insserv.conf.d   magic                overlayroot.conf         rmt            timezone
at.deny                 docker          iproute2         magic.mime           PackageKit               rpc            tmpfiles.d
bash.bashrc             dpkg            iscsi            mailcap              pam.conf                 rsyslog.conf   ubuntu-advantage
bash_completion         e2scrub.conf    issue            mailcap.order        pam.d                    rsyslog.d      ucf.conf
bash_completion.d       environment     issue.net        manpath.config       passwd                   screenrc       udev
bindresvport.blacklist  ethertypes      kernel           mdadm                passwd-                  securetty      ufw
binfmt.d                fonts           kernel-img.conf  mime.types           perl                     security       update-manager
byobu                   fstab           landscape        mke2fs.conf          php                      selinux        update-motd.d
ca-certificates         fuse.conf       ldap             modprobe.d           pki                      sensors3.conf  update-notifier
ca-certificates.conf    fwupd           ld.so.cache      modules              pm                       sensors.d      vdpau_wrapper.cfg
calendar                gai.conf        ld.so.conf       modules-load.d       polkit-1                 services       vim
console-setup           groff           ld.so.conf.d     mtab                 pollinate                shadow         vmware-tools
cron.d                  group           legal            multipath            popularity-contest.conf  shadow-        vtrgb
cron.daily              group-          letsencrypt      multipath.conf       profile                  shells         vulkan
cron.hourly             grub.d          libaudit.conf    mysql                profile.d                skel           wgetrc
cron.monthly            gshadow         libnl-3          nanorc               protocols                sos.conf       X11
crontab                 gshadow-        locale.alias     netplan              pulse                    ssh            xattr.conf
cron.weekly             gss             locale.gen       network              python3                  ssl            xdg
cryptsetup-initramfs    hdparm.conf     localtime        networkd-dispatcher  python3.8                subgid         zsh_command_not_found
crypttab                host.conf       logcheck         NetworkManager       rc0.d                    subgid-
dbus-1                  hostname        login.defs       networks             rc1.d                    subuid

結論

上記のガイドでは、ローカル同期とリモート同期のためにLsyncdをインストールして構成する方法を学びました。これで、バックアップの目的で実稼働環境でLsyncdを使用できます。ご不明な点がございましたら、お気軽にお問い合わせください。


Ubuntu
  1. Ubuntu18.04でNginxを使用してWordPressをインストールする方法

  2. Linuxでローカルディレクトリとリモートディレクトリを同期する方法

  3. PPAを使用してUbuntuにqBitTorrent4.0をインストールする方法

  1. Ubuntu18.04にMavenをインストールする方法

  2. Ubuntu16.04でNetdataを使用してNginxを監視する方法

  3. Ubuntu20.04でDockerを使用してGiteaをインストールする方法

  1. UbuntuでFreeFileSyncを使用してファイル/フォルダーを同期する方法

  2. Ubuntu16.04で重複を使用してバックアップする方法

  3. UbuntuでNTPサーバーを使用して時刻を同期する方法