Quantcast
Channel: システム開発メモ
Viewing all articles
Browse latest Browse all 100

/etc/hostsとhttpd.conf、ssl.confからドメインとIPの対応を一覧化する

$
0
0

全サーバの/etc/hostsとhttpd.conf、ssl.confからドメインとIPの対応を一覧化するスクリプトを、egrep, xargs, sedのような一般的なコマンドを使って作成してみる。

/etc/hostsは以下のようになっているとする。

xxx.xxx.xxx.xx1   host1
xxx.xxx.xxx.xx2   host2
xxx.xxx.xxx.xx3   host3

スクリプトは次のように、for loopとsshで各サーバにegrep, xargs, sedなどのコマンドを発行している。現在いるサーバで定義した変数を展開できるように、sshのコマンド部分はダブルクォーテーションで括る必要がある。

domain_regex='[^ /]+\.(jp|com)'
confs='/etc/httpd/conf/httpd.conf /etc/httpd/conf.d/ssl.conf'
target=`grep -o 'host.*$' /etc/hosts`

for i in $target
do
  ssh $i "
          egrep -oh ' $domain_regex' $confs 2>/dev/null |
          sort -u |
          xargs -I% echo '%    `sed -nr \"s/^([0-9\.]+) +$i$/\1/p\" /etc/hosts`'
         "
done

出力結果は以下のようになる。

xxx1.xxx.jp    xxx.xxx.xxx.xx1
xxx2.xxx.jp    xxx.xxx.xxx.xx2
xxx3.xxx.jp    xxx.xxx.xxx.xx3
xxx4.xxx.jp    xxx.xxx.xxx.xx4
xxx5.xxx.jp    xxx.xxx.xxx.xx5
xxx6.xxx.jp    xxx.xxx.xxx.xx6
xxx7.xxx.jp    xxx.xxx.xxx.xx7

egrep -oでhttpd.confとssl.confからドメインの正規表現に一致する部分を取り出している。' $domain_regex'の部分で、$domain_regexの前にスペース一文字を入れているのは、ServerName xxx.xxx.jpあるいはServerAlias yyy.xxx.jp zzz.xxx.jpのように各ドメインの区切りとなっている文字がスペースだから。
httpd.confとssl.confのように複数ファイルをegrepに渡した時に、どのファイルにマッチしているかという情報が出てしまうと後の処理が面倒なため、-hオプションをつけてファイル名を出力しないようにしている。

httpd.confとssl.confで重複したドメインがあるかもしれないので、各サーバ内でsort -uを実行して一意にしている。

sort -uまででconfに書かれているドメインが一列に出力されている状態になる。各行、ドメインの横にサーバのグローバルIPアドレスを記載するために、xargsとechoを組み合わせている。echoの中ではsedのコマンド置換を行っており、sedで/etc/hostsからグローバルIPアドレス部分のみを抽出している。ifconfigなど別の方法でグローバルIPアドレスが取得できるのであればそれでも問題ないし、sedではなくgrepで抽出してもいい。

xargs -I% echo '%    `grep $i$ /etc/hosts | egrep -o '^[0-9\.]+'`'

今回はhttpd.confとssl.confにしたが、confs変数にnginx/nginx.confやnginx/conf.d/ssl.confを入れることでnginxのconfも検索対象にできる。

Copyright © 2017 システム開発メモ All Rights Reserved.


Viewing all articles
Browse latest Browse all 100