LoginSignup
4
6

More than 5 years have passed since last update.

expectでrsync over sshのパスワード入力を楽にする

Posted at

前提

やんごとなき事情でファイル単位でrsync over sshをする、かつ、rsync over sshがパスワード認証の場合、ファイルごとにコマンドを実行してコマンドごとにパスワード入力が求められます。expectを使うとパスワード入力が1回で済むので楽できます。

準備

CentOS5/6などではyumでexpectをインストールしてください。

sudo yum install expect

例題のパラメータ

  • ssh先のIPアドレス: a.b.c.d
  • ssh先のポート番号: 10022
  • sshのログインID: user
  • ssh先の同期対象のディレクトリの絶対パス:/var/www/html

例題

まず更新対象のファイルのリストを以下のように作成します。ディレクトリの場合は末尾に「/」をつけないでください。ファイル名を「filelist.txt」とします。

app/Config/core.php
app/View/Top/index.ctp
...

以下のコマンドを実行して更新用のシェルスクリプトを生成します。

$ cat <<EOT>rsync.sh
#!/bin/bash

read -sp "Password: " PASS
tty -s && echo

EOT
$ for i in `cat filelist.txt`; do
cat <<EOT
expect -c "
set timeout 10
spawn rsync -auzv -e \"ssh -p 10022 -l user -o StrictHostKeyChecking=no\" --exclude \".svn\" --exclude \".git\" ${i} a.b.c.d:/var/www/html/`dirname ${i}`/
expect password:
send \"\${PASS}\n\"
interact
"
EOT
done | tee -a rsync.sh

生成したシェルスクリプトを同期対象のディレクトリにcdして実行します。

/bin/bash rsync.sh

備考

rsyncは事前にdry run(rsync -n)で結果を確認してから実行する方が良いので、dry run用のスクリプトも作って実行するのがお勧めです。

4
6
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
4
6