4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

複数のDigest認証のページをスクリプトで生成したい

4
Last updated at Posted at 2015-03-28

Digest認証がかかった複数のページをスクリプトで生成します。

ディレクトリ構成

生成するディレクトリ構成はこんな感じです。

./foo/bar1 ...ユーザ: bar1、パスワード: pass1で認証
./foo/bar2 ...ユーザ: bar2、パスワード: pass2で認証
...

事前に準備するファイル

  • パスワードを記載したファイル

1行に1つパスワードを記載します。

password.txt
pass1
pass2
  • .htaccessのひな形
.htaccess
    AuthType Digest
    AuthName "foo"
    AuthDigestDomain /foo/bar/
    AuthUserFile /var/www/html/foo/bar/.htdigest
    Require valid-user

生成スクリプト

Digest認証の設定ファイルはhtdigestコマンドで生成するのですが、対話式のためそのままでは自動実行できません。bashのexpectを使って自動化します。

generate_digest.sh
# !/bin/bash
i=1
for line in `cat password.txt`; do
  dir_name="bar${i}"
  mkdir "${dir_name}"
  cp .htaccess "${dir_name}/.htaccess"
  sed -i -e "s|bar/|bar${i}/|g" ${dir_name}/.htaccess
  expect -c "
  spawn htdigest -c ${dir_name}/.htdigest foo ${dir_name} 
  expect \"New password:\"
  send -- \"${line}\n\"
  expect \"Re-type new password:\"
  send -- \"${line}\n\"
  wait
  "
  i=$(( i + 1 ))
done
  • for loopでpasswordファイルを1行ずつ読み込みます。
    • barX ディレクトリを作成し、.htaccessファイルをコピーします。
    • .htaccessの内容を、フォルダ名に合わせて置換します。
    • htdigestコマンドを実行します。
    • パスワードを、expect/sendで自動入力されるようにします。
    • waitでhtdigestコマンドの終了を待ちます。waitで待たないと、spawnでサブプロセスとして実行されたhtdigestコマンドがファイルを生成する前に中断されたりして、正しくファイルを生成できませんでした。

スクリプトの実行

expectが入ってない場合はインストールしておきます。

sudo aptitude install expect

fooディレクトリにパスワードを記載したファイル、.htaccessのひな形、スクリプトを配置し、スクリプトを実行します。

$ ./generate_digest.sh

fooディレクトリを/var/www/html/にコピーします。

スクリプトの検証

当初、wait処理を入れていなかったため、一部のページだけDigest認証の設定ファイルが正しく生成されない現象に陥ったので、検証用のスクリプトを作りました。
curlでページを叩いて、200が返ってきているかを確認するスクリプトです。

verify_digest.sh
# !/bin/bash

i=1
url="http://localhost/foo/"
for line in `cat password.txt`; do
  curl --digest -u bar${i}:${line} ${url}bar${i}/ -o /dev/null -w '%{http_code},' -s
  i=$(( i + 1 ))
done

実行結果はこんな感じです。

$ ./verify_digest.sh 
200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,...
4
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?