LoginSignup
15
19

More than 3 years have passed since last update.

rsync + ssh で同期する

Last updated at Posted at 2020-04-19

rsync + ssh で同期する

rsync + ssh で同期する (最終形)

項目 意味
target_host リモートのホスト名またはIPアドレス
user リモートのユーザー名
remote_path リモートのファイルパス
local_path ローカルPCのファイルパス
PASSWD リモートのパスワードか入った環境変数
PORT リモートのSSH のポートが入った環境変数

ローカル → リモートにコピー

PASSWD="xxxxxx"
PORT=22
sshpass -p "$PASSWD" rsync  --delete -ave "ssh -p $PORT -o 'StrictHostKeyChecking no'" local_path user@target_host:remote_path

リモート → ローカルにコピー

PASSWD="xxxxxx"
PORT=22
sshpass -p "$PASSWD" rsync  --delete -ave "ssh -p $PORT -o 'StrictHostKeyChecking no'" user@target_host:remote_path local_path

解説

ローカル → リモートにコピーの場合を説明する。
リモート → ローカルは引数を逆にするだけです。

初期版

rsync  -e ssh local_path user@target_host:remote_path

ディレクトリを転送する場合

ディレクトリを転送する場合は上記コマンドだと以下のようにスキップされます。

skipping directory local_path

-r オプションをつけることでディレクトリも転送できます。

rsync  -r -e ssh local_path user@target_host:remote_path

転送元で削除したファイルを削除する場合

--delete オプションをつけることで転送元で削除したファイルを転送先で削除します。

rsync --delete  -r -e ssh local_path user@target_host:remote_path

cp -a のように属性を保持して転送する

-a オプションをつけることでcp -a のように属性を保持して転送します。
-a オプションは -r を含むので -r は不要です。

rsync --delete  -a -e ssh local_path user@target_host:remote_path

進捗を表示する

-v オプションをつけることで進捗を表示します。

rsync --delete  -a -v -e ssh local_path user@target_host:remote_path

sshpass を使用してパスワードをコマンドラインから指定する

sshpass を使用することでパスワードをコマンドラインから指定します。

PASSWD はパスワードを保持する環境変数

PASSWD="xxxxxx"
sshpass -p "$PASSWD" rsync --delete  -a -v -e ssh local_path user@target_host:remote_path

'StrictHostKeyChecking no' を指定して SSHの警告メッセージを出さない

PASSWD="xxxxxx"
sshpass -p "$PASSWD" rsync --delete  -a -v -e "ssh -o 'StrictHostKeyChecking no'" local_path user@target_host:remote_path

'-p' オプションを指定して SSH のポート番号を指定する

PASSWD="xxxxxx"
PORT=22
sshpass -p "$PASSWD" rsync --delete  -a -v -e "ssh -p $PORT -o 'StrictHostKeyChecking no'" local_path user@target_host:remote_path

rsync のオプションをまとめる

-a -v -e-ave とまとめられる。

PASSWD="xxxxxx"
PORT=22
sshpass -p "$PASSWD" rsync --delete  -ave "ssh -p $PORT -o 'StrictHostKeyChecking no'" local_path user@target_host:remote_path

リンク

https://www.pistolfly.com/weblog/2008/04/rsync-ssh-1.html
https://devilab.net/archives/1207

15
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
19