ラベル shellscript の投稿を表示しています。 すべての投稿を表示
ラベル shellscript の投稿を表示しています。 すべての投稿を表示

2014年3月18日火曜日

LinuxのftpコマンドでディレクトリをFTP転送する方法

LinuxのftpコマンドでディレクトリをFTP転送することはできません。
転送したいファイルをあらかじめzip化したファイルを作成して転送する方法を記載します。

転送元サーバホスト名: dcf-web
転送元サーバOS: RHEL6.4 (64-bit)
転送元ディレクトリ: /tmp/ftp/
転送対象ファイル: fonts.zip sound.zip

転送先サーバホスト名: dcf-bak
転送先サーバIP: 192.168.47.50
転送先サーバOS: RHEL6.4 (64-bit)
転送先ディレクトリ: /backup/ftp/dcf-web/

OS: RedHat EL 6.4(64-bit)
vsFTPd: 2.2.2


■転送先サーバでFTPプロセスが起動していること

[root@dcf-bak ~]# /etc/init.d/vsftpd status
vsftpd (pid 19316) を実行中...
[root@dcf-bak ~]#
※送信元サーバのvsftpdプロセスは停止していてもOK。

■転送元ディレクトリ確認

※転送対象ディレクトリに /etc/fonts/ と /etc/sound/ を選んだ理由は特になし。
[root@dcf-web ~]# ll -d /etc/fonts/ /etc/sound/
drwxr-xr-x. 4 root root 4096  5月 29 06:25 2013 /etc/fonts/
drwxr-xr-x. 3 root root 4096  5月 29 06:27 2013 /etc/sound/
[root@dcf-web ~]#

■FTP転送用データ準備

転送対象ディレクトリをzipコマンドでアーカイブファイルを作成。
[root@dcf-web ~]# mkdir /tmp/ftp
[root@dcf-web ~]# zip -r /tmp/ftp/fonts.zip /etc/fonts/
  adding: etc/fonts/ (stored 0%)
  adding: etc/fonts/fonts.dtd (deflated 70%)
  adding: etc/fonts/conf.avail/ (stored 0%)
  adding: etc/fonts/conf.avail/10-sub-pixel-rgb.conf (deflated 27%)
(省略)
[root@dcf-web ~]# zip -r /tmp/ftp/sound.zip /etc/sound/
  adding: etc/sound/ (stored 0%)
  adding: etc/sound/events/ (stored 0%)
  adding: etc/sound/events/gtk-events-2.soundlist (deflated 60%)
  adding: etc/sound/events/gnome-2.soundlist (deflated 69%)
[root@dcf-web ~]#
[root@dcf-web ~]# ll /tmp/ftp/
合計 76
-rw-r--r-- 1 root root 53699  3月 18 15:49 2014 fonts.zip
-rw-r--r-- 1 root root 16499  3月 18 15:49 2014 sound.zip
[root@dcf-web ~]#

■ftpコマンド(解説付き)

[root@dcf-web ~]# ftp -ivn 192.168.47.50
Connected to 192.168.47.50 (192.168.47.50).
220 (vsFTPd 2.2.2)
オプション
 -i: 複数のファイルの転送中にプロンプトを出さないようにする。
 -v: リモートサーバからの全てのレスポンスを詳細表示する。
 -n: 自動ログインさせない。ログインにアカウントとパスワードを要求する。

ftp> user ftpuser secret
331 Please specify the password.
230 Login successful.
アカウント: ftpuser
パスワード: secret

ftp> lcd /tmp/ftp/
Local directory now /tmp/ftp
転送元サーバのディレクトリを移動。

ftp> cd /backup/ftp/dcf-web/
250 Directory successfully changed.
転送先サーバのディレクトリを移動。

ftp> bin
200 Switching to Binary mode.
バイナリモードに変更。

ftp> mput *.zip
local: fonts.zip remote: fonts.zip
227 Entering Passive Mode (192,168,47,50,28,169).
150 Ok to send data.
226 Transfer complete.
53699 bytes sent in 0.000782 secs (68668.80 Kbytes/sec)
local: sound.zip remote: sound.zip
227 Entering Passive Mode (192,168,47,50,254,125).
150 Ok to send data.
226 Transfer complete.
16499 bytes sent in 3.1e-05 secs (532225.82 Kbytes/sec)
zipファイルを転送

ftp> ls
227 Entering Passive Mode (192,168,47,50,104,238).
150 Here comes the directory listing.
-rw-r--r--    1 1120     1100        53699 Mar 18 06:57 fonts.zip
-rw-r--r--    1 1120     1100        16499 Mar 18 06:57 sound.zip
226 Directory send OK.
転送先のファイルリストを表示。

ftp> quit
221 Goodbye.
[root@dcf-web ~]#
FTPモード終了。

■転送先サーバでの確認

[root@dcf-bak ~]# ll /backup/ftp/dcf-web/
合計 76
-rw-r--r-- 1 ftpuser sshgrp 53699  3月 18 15:57 2014 fonts.zip
-rw-r--r-- 1 ftpuser sshgrp 16499  3月 18 15:57 2014 sound.zip
[root@dcf-bak ~]#

■転送先サーバで解凍してみる

解凍先ディレクトリに /root/work/ftp/ を指定。
[root@dcf-bak ~]# unzip /backup/ftp/dcf-web/fonts.zip -d /root/work/ftp/
Archive:  /backup/ftp/dcf-web/fonts.zip
   creating: /root/work/ftp/etc/fonts/
  inflating: /root/work/ftp/etc/fonts/fonts.dtd
   creating: /root/work/ftp/etc/fonts/conf.avail/
  inflating: /root/work/ftp/etc/fonts/conf.avail/10-sub-pixel-rgb.conf
(省略)
[root@dcf-bak ~]# unzip /backup/ftp/dcf-web/sound.zip -d /root/work/ftp/
Archive:  /backup/ftp/dcf-web/sound.zip
   creating: /root/work/ftp/etc/sound/
   creating: /root/work/ftp/etc/sound/events/
  inflating: /root/work/ftp/etc/sound/events/gtk-events-2.soundlist
  inflating: /root/work/ftp/etc/sound/events/gnome-2.soundlist
[root@dcf-bak ~]#
[root@dcf-bak ~]# ll /root/work/ftp/etc/
合計 8
drwxr-xr-x 4 root root 4096  5月 29 06:25 2013 fonts
drwxr-xr-x 3 root root 4096  5月 29 06:27 2013 sound
[root@dcf-bak ~]#
転送元サーバと同じタイムスタンプのディレクトリが作成された。

■FTP転送シェルスクリプト

#!/bin/sh
# 複数ファイルをFTP転送するシェルスクリプト
# 転送対象ファイルはあらかじめzip化し、*.zipとすること
# 転送元: LOCAL
# 転送先: REMOTE

LOCAL_DIR="/tmp/ftp"
REMOTE_HOST="192.168.47.50"
REMOTE_USER="ftpuser"
REMOTE_PASS="secret"
REMOTE_DIR="/backup/ftp/dcf-web"
LOG="ftp.log"

ftp -ivn ${REMOTE_HOST} << END > ${LOG}
user ${REMOTE_USER} ${REMOTE_PASS}
lcd ${LOCAL_DIR}
cd ${REMOTE_DIR}
bin
mput *.zip
quit
END

exit 0

■FTP転送実行とログ確認

[root@dcf-web work]# ./ftp.sh
[root@dcf-web work]# cat ftp.log
Connected to 192.168.47.50 (192.168.47.50).
220 (vsFTPd 2.2.2)
331 Please specify the password.
230 Login successful.
Local directory now /tmp/ftp
250 Directory successfully changed.
200 Switching to Binary mode.
local: fonts.zip remote: fonts.zip
227 Entering Passive Mode (192,168,47,50,175,113).
150 Ok to send data.
226 Transfer complete.
53699 bytes sent in 0.0005 secs (107397.99 Kbytes/sec)
local: sound.zip remote: sound.zip
227 Entering Passive Mode (192,168,47,50,171,39).
150 Ok to send data.
226 Transfer complete.
16499 bytes sent in 3.5e-05 secs (471400.00 Kbytes/sec)
221 Goodbye.
[root@dcf-web work]#
※転送先に同名ファイルが存在すると上書きする。

こちらの情報が何かのお役に立てましたら幸いです。サイト継続のご協力ありがとうございます。m(_ _)m

2014年3月13日木曜日

Apacheのログ出力先を変更し日次でrotateする設定

Apacheのログはデフォルトでは、/etc/logrotate.conf と /etc/logrotate.d/httpd の
設定により週次でローテートされ4世代のバックアップを保持します。およそ1か月以上前のログは
参照できなくなります。大規模サイト等では長期間のログを保持する必要があるためこの設定は
不都合になることがあります。

一般的にApacheのログ出力先とWebサイトコンテンツは別ボリュームに分けたほうがよいと
考えられます。Apacheのログ出力先を変更(/log/ 以下)して日次で出力する設定をまとめます。

また、ログは削除せず、任意のタイミングでアーカイブするシェルスクリプトも準備します。

OS: RedHat EL 6.4(64-bit)
Apache: 2.2.15
仮ドメイン名: domain1.com、domain2.com


■Apacheのログを日次で出力
httpd.confの下記個所を変更します。
ログファイル名に日付を付与し、1日(=86400秒)ごとに出力します。
VirtualHost別のログ出力先を考慮して /log/httpd/[ドメイン名]/ 以下に変更します。
[root@dcf-web ~]# grep -B 1 rotatelogs /etc/httpd/conf/httpd.conf
#ErrorLog logs/error_log
ErrorLog "| /usr/sbin/rotatelogs -l /log/httpd/domain1.com/error_log-%Y%m%d 86400"
--
#CustomLog logs/access_log combined
CustomLog "| /usr/sbin/rotatelogs -l /log/httpd/domain1.com/access_log-%Y%m%d 86400" combined
[root@dcf-web ~]#
※domain2.comの設定は省略。
※/log/httpd/domain1.com-access_log-%Y%m%d と /log/httpd/domain2.com-access_log-%Y%m%d
 のようにして、ファイル名でドメインを区別する方法もアリです。

⇒ログ出力状況(以下のhttpdlog_archive.shを実行済み)
[root@dcf-web ~]# ll /log/httpd/domain1.com/ | head
合計 1045260
-rw-r--r-- 1 root root    40813  1月  1 23:59 2014 access_log-20140101
-rw-r--r-- 1 root root    40698  1月  2 23:59 2014 access_log-20140102
-rw-r--r-- 1 root root    43786  1月  3 23:59 2014 access_log-20140103
-rw-r--r-- 1 root root    40418  1月  4 23:59 2014 access_log-20140104
-rw-r--r-- 1 root root    52147  1月  5 23:59 2014 access_log-20140105
-rw-r--r-- 1 root root    40623  1月  6 23:59 2014 access_log-20140106
-rw-r--r-- 1 root root    40426  1月  7 23:59 2014 access_log-20140107
-rw-r--r-- 1 root root    42826  1月  8 23:59 2014 access_log-20140108
-rw-r--r-- 1 root root    40254  1月  9 23:59 2014 access_log-20140109
[root@dcf-web ~]#

■3ヵ月前のhttpdログをアーカイブするシェルスクリプト
シェルスクリプトファイル名: httpdlog_archive.sh
#!/bin/sh
#######################################################################
# << 機能概要 >>
# 3ヵ月前のApacheのログファイル1か月分をアーカイブ後、生ログ削除
# ログ出力先: /log/httpd/domain1.com/
#           /log/httpd/domain2.com/
#
# << 変更履歴 >>
# Version  変更日       変更者        変更内容
# --------+------------+-----------+----------------------------------
#     1.0  2014/03/06   tanyao    New
#
#######################################################################

# 対象月を取得(yyyymm)
TARGET_MONTH=`date -d '3 months ago' '+%Y%m'`

# ログ保存先ディレクトリパス
LOG_DIR=/log/httpd

# 対象ディレクトリへ移動
cd ${LOG_DIR}

# 出力対象ファイルが既に存在する場合は終了
if [ -f domain1.com_${TARGET_MONTH}.tar.gz ] || [ -f domain2.com_${TARGET_MONTH}.tar.gz ]; then
    echo "tar file already exit."
    exit 1
fi

# 対象ログファイルアーカイブ
tar -zcf domain1.com_${TARGET_MONTH}.tar.gz domain1.com/*_log-${TARGET_MONTH}*
tar -zcf domain2.com_${TARGET_MONTH}.tar.gz domain2.com/*_log-${TARGET_MONTH}*

# 生ログは削除
rm -rf domain1.com/*_log-${TARGET_MONTH}*
rm -rf domain2.com/*_log-${TARGET_MONTH}*

cd -

exit 0

■crontabに登録
[root@dcf-web ~]# crontab -l | tail -2
# httpd log archive
22 2 2 * * (/opt/private/batch/httpdlog_archive.sh > /dev/null 2>&1)
[root@dcf-web ~]#
⇒ログアーカイブ状況
[root@dcf-web ~]# ll /log/httpd/
合計 272
drwxr-xr-x 2 root root  20480  3月 12 15:01 2014 domain1.com
-rw-r--r-- 1 root root     45  2月  2 22:00 2014 domain1.com_201311.tar.gz
-rw-r--r-- 1 root root 189336  3月  2 22:01 2014 domain1.com_201312.tar.gz
drwxr-xr-x 2 root root  20480  3月 12 14:59 2014 domain2.com
-rw-r--r-- 1 root root   8780  2月  2 22:01 2014 domain2.com_201311.tar.gz
-rw-r--r-- 1 root root  23253  3月  2 22:01 2014 domain2.com_201312.tar.gz
[root@dcf-web ~]#

こちらの情報が何かのお役に立てましたら幸いです。サイト継続のご協力ありがとうございます。m(_ _)m

2013年12月14日土曜日

wgetでWebサイトのレスポンスを調査するシェルスクリプト

wgetを利用して複数Webサイトのレスポンスを調査するシェルスクリプトのサンプルです。
今回は試しにキャリア3社のWebサイトのレスポンスを調査してみました。

OS: CentOS 6.4(64-bit)
wget: GNU Wget 1.12 built on linux-gnu.


■シェルスクリプトサンプル
[root@centos64 ~]# cat response.sh
#!/bin/sh
# wgetを利用してWebサイトのレスポンスを調査する。

URL=url.list
LOG=response_`date +%Y%m%d-%H%M`.log
TODAY=`date +%Y-%m-%d`

# url.listの存在チェック
if [ ! -f ${URL} ]; then
    echo "${URL} no such file or directory"
    exit 1
fi

wget -t 2 -P response -o ${LOG} -i ${URL}
rm -rf response

#grep "[0-9]\]$" ${LOG}
#grep -B 3 "404 Not Found" ${LOG}
grep ${TODAY} ${LOG}

exit 0
[root@centos64 ~]#
リトライは2回くらいで十分かと。

■URLリスト
[root@centos64 ~]# cat url.list
https://www.nttdocomo.co.jp/
https://www.nttdocomo.co.jp/product/
https://www.nttdocomo.co.jp/service/
https://www.nttdocomo.co.jp/binary/pdf/corporate/technology/document/pdc/jidoushadenwa.pdf

http://www.kddi.com/
http://www.au.kddi.com/
http://www.kddi.com/corporate/ir/library/annual_report/pdf/kddi_ar2013_j.pdf

http://www.softbank.jp/
http://www.softbank.jp/corp/
http://cdn.softbank.jp/corp/set/data/csr/pdf/csr2013_01.pdf
[root@centos64 ~]#
サイズの大きいPDFファイルへのリンク等を適当に入れています。

■実行結果
[root@centos64 ~]# ./response.sh
--2013-12-14 16:43:37--  https://www.nttdocomo.co.jp/
2013-12-14 16:43:42 (2.11 MB/s) - `response/index.html' へ保存終了 [44553]
--2013-12-14 16:43:42--  https://www.nttdocomo.co.jp/product/
2013-12-14 16:43:42 (2.02 MB/s) - `response/index.html.1' へ保存終了 [76905]
--2013-12-14 16:43:42--  https://www.nttdocomo.co.jp/service/
2013-12-14 16:43:43 (1.03 MB/s) - `response/index.html.2' へ保存終了 [162300]
--2013-12-14 16:43:43--  https://www.nttdocomo.co.jp/binary/pdf/corporate/technology/document/pdc/jidoushadenwa.pdf
2013-12-14 16:43:43 (2.18 MB/s) - `response/jidoushadenwa.pdf' へ保存完了 [733433/733433]
--2013-12-14 16:43:43--  http://www.kddi.com/
2013-12-14 16:43:48 (1023 KB/s) - `response/index.html.3' へ保存終了 [13808]
--2013-12-14 16:43:48--  http://www.au.kddi.com/
2013-12-14 16:43:53 (2.05 MB/s) - `response/index.html.4' へ保存完了 [56991/56991]
--2013-12-14 16:43:53--  http://www.kddi.com/corporate/ir/library/annual_report/pdf/kddi_ar2013_j.pdf
2013-12-14 16:43:55 (4.69 MB/s) - `response/kddi_ar2013_j.pdf' へ保存完了 [8913281/8913281]
--2013-12-14 16:43:55--  http://www.softbank.jp/
2013-12-14 16:44:00 (377 KB/s) - `response/index.html.5' へ保存終了 [43626]
--2013-12-14 16:44:00--  http://www.softbank.jp/corp/
2013-12-14 16:44:00 (460 KB/s) - `response/index.html.6' へ保存完了 [35866/35866]
--2013-12-14 16:44:00--  http://cdn.softbank.jp/corp/set/data/csr/pdf/csr2013_01.pdf
2013-12-14 16:44:07 (2.64 MB/s) - `response/csr2013_01.pdf' へ保存完了 [3378593/3378593]
終了しました --2013-12-14 16:44:07--
[root@centos64 ~]#
※レスポンス結果はその時々で変化します。
※上記はその時の結果であり、何かを保証するものではありません。

この情報が何かのお役にたてれば幸いです。m(_ _)m

2013年10月19日土曜日

複数URLのリンク切れをチェックするシェルスクリプト


ドメインの異なる複数のWebサイトに対してリンク切れが発生していないか
URLのリストに従ってチェックするシェルスクリプトのサンプルです。
wgetの--spiderオプションを利用しています。

OS: CentOS 6.4(64-bit)
wget: GNU Wget 1.12 built on linux-gnu.


■シェルスクリプトサンプル
#!/bin/sh
#######################################################################
# << 機能概要 >>
# URLリストを読み込んでリンク切れチェックするスクリプト
#
# << 変更履歴 >>
# Version  変更日       変更者        変更内容
# --------+------------+-----------+----------------------------------
#     1.0  2013/10/12   tanyao      New
#######################################################################

URL_LIST=url_list.txt
OUTPUT=url_result.txt

# URLリスト存在チェック
if [ ! -e $URL_LIST ]; then
    echo "`date \"+%Y%m%d %H:%M:%S\"` ERROR: $URL_LIST is not exist."
    exit 1
fi

# 出力結果クリア
:> $OUTPUT

# URLリスト読み込み
i=0
while read line
do
    url[$i]="$line"

    # リンク切れチェック結果出力
    wget -nv --spider --timeout 15 -t 1 ${url[$i]} -a $OUTPUT

    i=`expr $i + 1`
done < $URL_LIST

exit 0
url_check.sh というファイル名で保存し、パーミッションを755に変更。

■URLリストファイル準備
[root@centos64 url_check]# head url_list.txt
http://kakaku.com/item/J0000011385/
http://kakaku.com/item/J0000009488/
http://kakaku.com/item/K0000588606/
http://kakaku.com/item/K0000590023/
http://kakaku.com/item/K0000999999/
http://static.panoramio.com/photos/large/94004107.jpg
http://static.panoramio.com/photos/large/94007107.jpg
http://static.panoramio.com/photos/large/9d004108.jpg
http://www.atmarkit.co.jp/ait/articles/1302/05/news222.html
http://topics.jp.msn.com/world/topics.aspx?topicid=1985
url_check.sh と同階層にurl_list.txtを配置する。

■スクリプト実行
url_result.txtが出力される。
[root@centos64 url_check]# ./url_check.sh
[root@centos64 url_check]# head url_result.txt
2013-10-07 00:39:20 URL: http://kakaku.com/item/J0000011385/ 200 OK
2013-10-07 00:39:21 URL: http://kakaku.com/item/J0000009488/ 200 OK
2013-10-07 00:39:21 URL: http://kakaku.com/item/K0000588606/ 200 OK
2013-10-07 00:39:21 URL: http://kakaku.com/item/K0000590023/ 200 OK
http://kakaku.com/item/K0000999999/:
リモートファイルが存在していません -- リンクが壊れています!!!
2013-10-07 00:39:22 URL: http://static.panoramio.com/photos/large/94004107.jpg 200 OK
2013-10-07 00:39:22 URL: http://static.panoramio.com/photos/large/94007107.jpg 200 OK
http://static.panoramio.com/photos/large/9d004108.jpg:
リモートファイルが存在していません -- リンクが壊れています!!!
wgetのバージョンによっては、ステータスコードが200の場合、何も出力されない場合があります。

リンクチェック対象が多いとそれなりに時間がかかります。この情報がお役にたてれば幸いです。

2012年10月14日日曜日

vmstatやtopコマンドに時間を表示する方法


定期的に結果を出力するコマンドに時間を表示させる方法です。
パフォーマンステストの状況確認を行う場合に便利かも。

OS: CentOS 6.3(64-bit)
vmstat: 3.2.8
top: 3.2.8


■vmstatに時間を表示させる
[root@cent63 ~]# vmstat 1 3 | awk '{print strftime("%Y/%m/%d %H:%M:%S"), $0}' 2012/10/14 21:45:58 procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu----- 2012/10/14 21:45:58 r b swpd free buff cache si so bi bo in cs us sy id wa st 2012/10/14 21:45:58 1 0 4832 99536 115484 398552 0 0 0 1 9 3 0 0 100 0 0 2012/10/14 21:45:59 0 0 4832 99520 115484 398552 0 0 0 0 48 85 0 1 99 0 0 2012/10/14 21:46:00 0 0 4832 99520 115484 398552 0 0 0 0 51 82 1 0 99 0 0 [root@cent63 ~]#
perlを使う方法もあります。
[root@cent63 ~]# vmstat 1 3 | perl -MPOSIX -pe 'BEGIN{$|=1} print strftime q{%Y/%m/%d %H:%M:%S }, localtime' 2012/10/14 21:46:08 procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu----- 2012/10/14 21:46:08 r b swpd free buff cache si so bi bo in cs us sy id wa st 2012/10/14 21:46:08 1 0 4832 99536 115484 398552 0 0 0 1 9 3 0 0 100 0 0 2012/10/14 21:46:09 0 0 4832 97412 115496 398980 0 0 440 0 170 175 5 3 72 20 0 2012/10/14 21:46:10 0 0 4832 97412 115496 398980 0 0 0 0 50 85 0 0 100 0 0 [root@cent63 ~]#

■topに時間を表示させる
[root@cent63 ~]# top -n 1 -b | head -5 | awk '{print strftime("%Y/%m/%d %H:%M:%S"), $0}' 2012/10/14 21:48:17 top - 21:48:17 up 43 days, 3 min, 2 users, load average: 0.00, 0.00, 0.00 2012/10/14 21:48:17 Tasks: 160 total, 1 running, 159 sleeping, 0 stopped, 0 zombie 2012/10/14 21:48:17 Cpu(s): 0.1%us, 0.1%sy, 0.0%ni, 99.8%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st 2012/10/14 21:48:17 Mem: 1020644k total, 922124k used, 98520k free, 115500k buffers 2012/10/14 21:48:17 Swap: 2064376k total, 4832k used, 2059544k free, 398980k cached [root@cent63 ~]#

いろいろと応用が利くかも…。またしても小ネタですみません。

2012年10月13日土曜日

grepコマンドでコメント行と空白行を非表示にする


grepコマンドを利用してでコメント行と空白行を非表示にする方法です。
httpd.confやsmb.conf等の設定ファイルはやたらとコメント文が多いので
それらを非表示にしてズバリ設定内容だけ確認したい場合に便利です。

OS: CentOS 6.3(64-bit)
grep: 2.6.3


■コメント行と空白行を非表示
[root@cent63 ~]# grep -v "^#\|^$" /etc/httpd/conf/httpd.conf ServerTokens OS ServerRoot "/etc/httpd" PidFile run/httpd.pid Timeout 60 KeepAlive Off MaxKeepAliveRequests 100 KeepAliveTimeout 15 (以下省略)
「#」で始まるコメント行を非表示 → 「^#」
空行を非表示 → 「^$」

■コメント前にタブがあっても非表示にする
[root@cent63 ~]# grep -v "^[^t]*#\|^$" /etc/httpd/conf/httpd.conf ServerTokens OS ServerRoot "/etc/httpd" PidFile run/httpd.pid Timeout 60 KeepAlive Off MaxKeepAliveRequests 100 KeepAliveTimeout 15 (以下省略)
これだと前述となんら変わらないように見えるので、出力行数で確認
[root@cent63 ~]# grep -v "^#\|^$" /etc/httpd/conf/httpd.conf | wc -l 238 [root@cent63 ~]# grep -v "^[^t]*#\|^$" /etc/httpd/conf/httpd.conf | wc -l 225 [root@cent63 ~]#
確かにタブの後に#がある行も非表示となった。

■smb.confの有効行だけ表示するにはもう一工夫が必要
[root@cent63 ~]# grep -v "^[^t]$\|^[^t]*#\|^$\|^#\|^;" /etc/samba/smb.conf [global] workgroup = MYGROUP server string = Samba Server Version %v log file = /var/log/samba/log.%m max log size = 50 security = user passdb backend = tdbsam load printers = yes cups options = raw [homes] comment = Home Directories browseable = no writable = yes [printers] comment = All Printers path = /var/spool/samba browseable = no guest ok = no writable = no printable = yes [root@cent63 ~]#

以上です。小ネタですみません。

2011年12月21日水曜日

ファイル名にタイムスタンプを付与してコピー


■スクリプト概要
バックアップする際、元ファイルのタイムスタンプをファイル名に使用したい場合があった時に
便利なスクリプトです。特に複数ファイルまとめて処理しようとする場合に活躍するはず…。


#!/bin/sh
#######################################################################
# << 機能概要 >>
# バックアップしたファイル名に元ファイルのタイムスタンプを付与する
#
# <<変更履歴>>
# Version  変更日      変更者        変更内容
# --------+-----------+-------------+----------------------------------
#     1.0  2011/xx/xx  tanyao        対象ファイルリスト読込み
#######################################################################

FILE_LIST=file_list.txt
LOG_FILE=log_add_timestamp.log

# リストファイル存在チェック
if [ ! -f $FILE_LIST ]; then
    echo "ERORR: $FILE_LIST is not exist."
    exit 1
fi


i=0
while read line
do
    cp_target[$i]="$line"

    # コピー対象ファイル存在チェック
    if [ -f ${cp_target[$i]} ]; then
        timestamp=`ls -lrt --time-style='+%Y%m%d' ${cp_target[$i]} | awk '{print $6}'`
        cp -p ${cp_target[$i]} ${cp_target[$i]}.${timestamp} > /dev/null 2>&1
        ls -l ${cp_target[$i]} ${cp_target[$i]}.${timestamp} >> ${LOG_FILE}
    else
        echo "ERORR: ${cp_target[$i]} is not exist." >> ${LOG_FILE}
#        continue
    fi

    i=`expr $i + 1`
done < ${FILE_LIST}

echo "" >> ${LOG_FILE}

exit 0


■以下、補足説明

このシェルスクリプト(add_timestamp.sh)はコピー対象のファイルパスが記載された
file_list.txtというファイルを同階層にご準備ください。
[root@tanyao ~]# cat file_list.txt
/tmp/test01.txt
/tmp/test02.txt
/tmp/test03.txt
/tmp/test04.txt

コピー対象ファイルのあるディレクトリの状況はこんな感じ。
[root@tanyao ~]# ll /tmp/test*
-rw-r--r-- 1 root root 132  2月  2  2002 /tmp/test01.txt
-rw-r--r-- 1 root root 132  6月  6  2006 /tmp/test02.txt
-rw-r--r-- 1 root root 132  6月  6  2006 /tmp/test02.txt.20060606
-rw-r--r-- 1 root root 132 12月 21 15:29 /tmp/test04.txt
※すでに複製後のファイルが存在していても上書きする仕様です。

スクリプトを実行すると同階層にログファイルが出力され、期待通り
タイムスタンプ名入りのコピーファイルが作成されたか確認できます。
[root@tanyao ~]# ./add_timestamp.sh
[root@tanyao ~]# cat log_add_timestamp.log
-rw-r--r-- 1 root root 132  2月  2  2002 /tmp/test01.txt
-rw-r--r-- 1 root root 132  2月  2  2002 /tmp/test01.txt.20020202
-rw-r--r-- 1 root root 132  6月  6  2006 /tmp/test02.txt
-rw-r--r-- 1 root root 132  6月  6  2006 /tmp/test02.txt.20060606
ERORR: /tmp/test03.txt is not exist.
-rw-r--r-- 1 root root 132 12月 21 15:29 /tmp/test04.txt
-rw-r--r-- 1 root root 132 12月 21 15:29 /tmp/test04.txt.20111221

[root@tanyao ~]# 

ちなみに、ファイルのタイムスタンプを変更するには、
[root@tanyao ~]# touch -t 200202021751 /tmp/test01.txt


こちらの情報が何かのお役に立てましたら幸いです。

2011年6月7日火曜日

Linux OSユーザ一括作成シェルスクリプト

通常OSユーザを作成する場合は、useraddコマンドおよびpasswdコマンドを手動で打ち、
一人ひとり作成していきますが、ユーザ数が多くなるとちょっと厄介、ぶっちゃけめんどいです。

今回紹介するスクリプトはユーザ情報がリスト化されたファイルを読み込んで一括でユーザを
作成することができます。
ただし、ユーザが所属するグループを事前に作成しておく必要があります。


■グループを事前に作成
[root@tanyao script]# /usr/sbin/groupadd -g 5000 public

■ユーザリストを準備
[root@tanyao script]# cat mk_user.list
# name:password:uid:gid:comment:home_directory:login_shell:sub_gid
user01:secret01:5001:5000:::/bin/bash
user02:secret02:5002:5000:::/bin/bash
user03:secret03:5003:5000:::/bin/bash
#user04:secret04:5004:5000:::/bin/bash
user05:secret05:5005:5000:::/bin/bash
[root@tanyao script]#
※ /etc/passwd ファイルのフォーマットに合わせてみた。つもり。

■ユーザ一括作成スクリプト(mk_user.sh)
[root@tanyao script]# cat mk_user.sh
#!/bin/sh
# mk_user.listに記述されたユーザを一括で作成します。
# 行頭に"#"がある行はコメント行とみなします。
# 既に存在しているユーザを作成しようとするとスキップされます。
# 事前にグループを作成ください。
# rootユーザで実行してください。

USERLIST=./mk_user.list

if [ ! -f ${USERLIST} ]; then
    echo "${USERLIST} no such file or directory"
    exit 1
fi

grep -v \^# ${USERLIST} | while read line
do
    name="`echo ${line} | cut -d ":" -f1`"
    passwd="`echo ${line} | cut -d ":" -f2`"
    uid="`echo ${line} | cut -d ":" -f3`"
    gid="`echo ${line} | cut -d ":" -f4`"
    comment="`echo ${line} | cut -d ":" -f5`"
    homedir="`echo ${line} | cut -d ":" -f6`"
    loginsh="`echo ${line} | cut -d ":" -f7`"
    subgid="`echo ${line} | cut -d ":" -f8`"

# サブグループがない場合
if [[ ${subgid} = "" ]]; then
    /usr/sbin/useradd -u ${uid} -g ${gid} -c "${comment}" ${name} || continue
# サブグループがある場合
else
    /usr/sbin/useradd -u ${uid} -g ${gid} -G ${subgid} -c "${comment}" ${name} || continue
fi

echo ${name}:${passwd} | chpasswd
echo "Making ${name} succeeded."
done

exit 0
[root@tanyao script]#
[root@tanyao script]# chmod 755 mk_user.sh

■ユーザ作成
[root@tanyao script]# ./mk_user.sh
Making user01 succeeded.
Making user02 succeeded.
Making user03 succeeded.
Making user05 succeeded.
[root@tanyao script]#

■確認
[root@tanyao script]# su - user01
[user01@tanyao ~]$ su - user02
Password:
[user02@tanyao ~]$ id
uid=5002(user02) gid=5000(public) groups=5000(public)
[user02@tanyao ~]$ pwd
/home/user02
[user02@tanyao ~]$

■ユーザ削除コマンド(参考)
[root@tanyao script]# userdel -r user05
[root@tanyao script]# id user05
id: user05: No such user
[root@tanyao script]#


◆ユーザ作成コマンドオプション確認
[root@tanyao script]# useradd --help
Usage: useradd [options] LOGIN

Options:
  -b, --base-dir BASE_DIR       base directory for the home directory of the
                                new account
  -c, --comment COMMENT         GECOS field of the new account
  -d, --home-dir HOME_DIR       home directory of the new account
  -D, --defaults                print or change default useradd configuration
  -e, --expiredate EXPIRE_DATE  expiration date of the new account
  -f, --inactive INACTIVE       password inactivity period of the new account
  -g, --gid GROUP               name or ID of the primary group of the new
                                account
  -G, --groups GROUPS           list of supplementary groups of the new
                                account
  -h, --help                    display this help message and exit
  -k, --skel SKEL_DIR           use this alternative skeleton directory
  -K, --key KEY=VALUE           override /etc/login.defs defaults
  -l, --no-log-init             do not add the user to the lastlog and
                                faillog databases
  -m, --create-home             create the user's home directory
  -M, --no-create-home          do not create the user's home directory
  -N, --no-user-group           do not create a group with the same name as
                                the user
  -o, --non-unique              allow to create users with duplicate
                                (non-unique) UID
  -p, --password PASSWORD       encrypted password of the new account
  -r, --system                  create a system account
  -s, --shell SHELL             login shell of the new account
  -u, --uid UID                 user ID of the new account
  -U, --user-group              create a group with the same name as the user
  -Z, --selinux-user SEUSER     use a specific SEUSER for the SELinux user mapping

[root@tanyao script]#

◆ユーザ編集コマンドオプション確認
[root@tanyao script]# usermod --help
Usage: usermod [options] LOGIN

Options:
  -c, --comment COMMENT         new value of the GECOS field
  -d, --home HOME_DIR           new home directory for the user account
  -e, --expiredate EXPIRE_DATE  set account expiration date to EXPIRE_DATE
  -f, --inactive INACTIVE       set password inactive after expiration
                                to INACTIVE
  -g, --gid GROUP               force use GROUP as new primary group
  -G, --groups GROUPS           new list of supplementary GROUPS
  -a, --append                  append the user to the supplemental GROUPS
                                mentioned by the -G option without removing
                                him/her from other groups
  -h, --help                    display this help message and exit
  -l, --login NEW_LOGIN         new value of the login name
  -L, --lock                    lock the user account
  -m, --move-home               move contents of the home directory to the
                                new location (use only with -d)
  -o, --non-unique              allow using duplicate (non-unique) UID
  -p, --password PASSWORD       use encrypted password for the new password
  -s, --shell SHELL             new login shell for the user account
  -u, --uid UID                 new UID for the user account
  -U, --unlock                  unlock the user account
  -Z, --selinux-user            new SELinux user mapping for the user account

[root@tanyao script]#

◆ユーザ削除コマンドオプション確認
[root@tanyao script]# userdel --help
Usage: userdel [options] LOGIN

Options:
  -f, --force                   force removal of files,
                                even if not owned by user
  -h, --help                    display this help message and exit
  -r, --remove                  remove home directory and mail spool
  -Z, --selinux-user            remove SELinux user from SELinux user mapping

[root@tanyao script]#


この情報がお役に立ちましたら、いえ、ご寄付はいりません。
サイト継続のご協力を賜りたく存じます。 m(_ _)m

2011年6月2日木曜日

シェルスクリプトサンプル:ログファイル等のアーカイブ

独自開発したアプリケーションのログ等でローテート処理が考慮されていない場合、
ログファイルが増殖し続け、気づいた時にはエライことになっていたなんてことは
誰しもあるはずです。

古くなってきたログファイルを洗い出して圧縮し、さらに一定期間が過ぎると自動削除
するシェルスクリプトを作成しcrontabに登録しておけば、ディスク使用率アラートで
夜中に起こされて対応することはなくなるはずです。


■シェルスクリプトサンプル
#!/bin/sh
# 指定日数より前のファイルを圧縮し、さらに指定日数より古いアーカイブファイルを削除

ARCHIVE_DAYS=10
DELETE_DAYS=60
TARGET_DIR=/root/scripts/logs
OUTPUT=${TARGET_DIR}/`date +%Y%m%d-%H%M`_ArchiveFiles.tar.gz

# 対象ディレクトリへ移動
cd ${TARGET_DIR}

# 圧縮するファイル(拡張子は、.logまたは.txt)のリストを作成
find . -mtime +${ARCHIVE_DAYS} -iregex ".*\.log$\|.*\.txt$" > ${TARGET_DIR}/file.list

# 圧縮対象ファイルが存在するかのチェック
num_line=`cat ${TARGET_DIR}/file.list | wc -l`
if [ ${num_line} -gt 0 ]; then

 # リストに従ってtar.gzファイルを作成
tar -zcf ${OUTPUT} -T ${TARGET_DIR}/file.list

 # リストに従って元ファイルを削除
for i in `cat ${TARGET_DIR}/file.list`
 do
 rm -rf ${i}
 done

else
 echo "ERROR: More than ${ARCHIVE_DAYS} days before the file does not exist !!"
fi

# 指定日数より古いアーカイブファイルを削除
find . -mtime +${DELETE_DAYS} -regex ".*\.tar.gz$" | xargs rm -rf

# リストファイルを削除
# rm -rf ${TARGET_DIR}/file.list

exit 0

こちらの情報が何かのお役に立てましたら幸いです。サイト継続のご協力ありがとうございます。m(_ _)m

2011年4月26日火曜日

シェルスクリプトサンプル:ユーザ一括ロック


#!/bin/sh
# ロック対象ユーザリストを読込んで対象ユーザをロックするスクリプト

LOCK_USER=lock_user.list

# ロック対象ユーザリスト存在チェック
if [ ! -e $LOCK_USER ]; then
echo "`date \"+%Y%m%d %H:%M:%S\"` ERROR: $LOCK_USER is not exist."
exit 1
fi

# ロック対象ユーザリスト読込み
i=0
while read line
do
user_name[$i]="$line"

# ユーザ存在チェック
id ${user_name[$i]} > /dev/null 2>&1
if [ $? -eq 0 ]; then
# ユーザをロック(無効化)
/usr/bin/passwd -l ${user_name[$i]}

# ユーザロック解除(参考)
# /usr/bin/passwd -u ${user_name[$i]}
else
echo "`date \"+%Y%m%d %H:%M:%S\"` ERROR: ${user_name[$i]} is not exist."
fi

i=`expr $i + 1`
done < $LOCK_USER

exit 0

-------------------------------------------------
■ユーザネーム一覧出力コマンド
[root@tanyao08~]# awk -F":" '{ print $1 }' /etc/passwd

■ロックユーザ一覧出力コマンド
[root@tanyao08 ~]# grep '!!' /etc/shadow

2011年3月31日木曜日

シェルスクリプトサンプル:ファイルローテート


#!/bin/sh
# ファイルサイズを判定してローテートするサンプル

# << SCRIPT SUB SECTION >>

##### ファイルサイズを判定してローテート
# $1:対象ファイル
# $2:ローテート条件
rotate() {

file_size=`ls -lk --time-style='+%Y%m%d' $1 | awk '{print $5}'`
file_time=`ls -lk --time-style='+%Y%m%d' $1 | awk '{print $6}'`

# ファイルサイズがローテート条件を超えたら
if [ ${file_size} -gt $2 ]; then
tar -zcf $1.${file_time}.tar.gz $1
# 0バイト化
:> $1
fi
}


# << SCRIPT MAIN SECTION >>

TRAGET_DIR=/home/operation # ローテート対象ディレクトリ
TRAGET_FILE=rsync.log # ローテート対象ファイル
THRESHOLD=20 # KBで指定

BASE=`pwd`
cd ${TRAGET_DIR}

rotate ${TRAGET_FILE} ${THRESHOLD}

ls -l ${TRAGET_FILE}*
cd ${BASE}

exit 0

2011年2月1日火曜日

シェルスクリプトサンプル:一括文字コード変換


#!/bin/sh

# 作業ディレクトリ(現在地)
BASE=`pwd`

# 変換対象元ディレクトリ
DIR=/home/efiles3/public/iw/072_STG-Web

# 変換対象ファイルの拡張子を指定する。
FILE_TYPE=".txt"

# 変換先文字コードオプション(UTF-8:-w SJIS:-s EUC:-e)
CHARA_CODE="-s"


# 出力先ディレクトリ作成
if [ ${CHARA_CODE} = "-w" ];then
OUTPUT_DIR="output_utf-8"
elif [ ${CHARA_CODE} = "-s" ];then
OUTPUT_DIR="output_sjis"
elif [ ${CHARA_CODE} = "-e" ];then
OUTPUT_DIR="output_euc"
else
echo "Character code is not existing error !!"
exit 0
fi
mkdir ./$OUTPUT_DIR

# 文字コード変換
cd $DIR
for i in `ls -1` ; do
/usr/bin/nkf $CHARA_CODE $i > $BASE/$OUTPUT_DIR/$i
done
cd $BASE


exit 0

2011年1月7日金曜日

シェルスクリプトサンプル:diffの差分比較結果をファイル出力

diffコマンドを利用して、2つのファイルの差分比較を行い、その結果を
ファイルに出力するシェルスクリプトのサンプルです。
Webコンテンツの移行作業において、移行前と移行後のファイルの差分が
発生していないか検証する際に便利です。


■サンプルスクリプト(sabun.sh)

[root@tanyao ~]# cat sabun.sh
#!/bin/sh

# 必ず比較対象ファイルと同階層にこのシェルを配置して実行してください!!

# 比較対象(パス指定禁止)
FILE1=file1.txt
FILE2=file2.txt

# ファイル名にスペースを含むファイルはNG扱いとする
if [ `grep " " ${FILE1} | wc -l` != 0 ] ; then
    grep " " ${FILE1} > diff_NG_${FILE1}
fi
if [ `grep " " ${FILE2} | wc -l` != 0 ] ; then
    grep " " ${FILE2} > diff_NG_${FILE2}
fi

# 並び替え
grep -v " " ${FILE1} | sort > sort_${FILE1}
grep -v " " ${FILE2} | sort > sort_${FILE2}

# 比較
diff -y -t -d sort_${FILE1} sort_${FILE2} > diff.txt

# 同一レコードの抽出
grep -v "<" diff.txt | grep -v ">" | grep -v "|" > diff_same.txt

# 第1ファイルにのみ存在
grep -e "<" -e "|" diff.txt | cut -d " " -f 1 > diff_only_${FILE1}

# 第2ファイルにのみ存在
grep ">" diff.txt | cut -d ">" -f 2 > diff_tmp_${FILE2}
grep "|" diff.txt | cut -d "|" -f 2 >> diff_tmp_${FILE2}
sed -e 's/^  //' diff_tmp_${FILE2} > diff_only_${FILE2}

# 作業ファイルの削除
rm -rf sort_${FILE1}
rm -rf sort_${FILE2}
rm -rf diff_tmp_${FILE2}

exit 0
[root@tanyao ~]#


■テストデータ準備

[root@tanyao ~]# cat file1.txt
/var/log/httpd/
/var/log/httpd/error_log
/var/log/httpd/error_log-20110103
/var/log/httpd/access_log
/var/log/httpd/access_log-20110103
[root@tanyao ~]#

[root@tanyao ~]# cat file2.txt
/var/log/httpd/
/var/log/httpd/error_log
/var/log/httpd/error_log-20110104
/var/log/httpd/access_log
/var/log/httpd/access_log.1
/var/log/httpd/access_log-20110103
[root@tanyao ~]#


■使用例および結果確認

[root@tanyao ~]# ./sabun.sh
[root@tanyao ~]# cat diff_only_file1.txt
/var/log/httpd/error_log-20110103
[root@tanyao ~]# cat diff_only_file2.txt
/var/log/httpd/access_log.1
/var/log/httpd/error_log-20110104
[root@tanyao ~]# cat diff_same.txt
/var/log/httpd/                                 /var/log/httpd/
/var/log/httpd/access_log                       /var/log/httpd/access_log
/var/log/httpd/access_log-20110103              /var/log/httpd/access_log-20110103
/var/log/httpd/error_log                        /var/log/httpd/error_log
[root@tanyao ~]#


■diffオプション

-y, --side-by-side
        side-by-side 出力形式を用いる。

side-by-side 形式

ファイルは 2 列に表示され、間に溝 (gutter) が置かれる。溝には以下のマーカーのいずれか 1 つが含まれる。

' '    対応する行が共通である。つまり、両方の行が同一であるか、違いが --ignore オプションのいずれかによって無視された。
|      対応する行が異なる。両方とも完全か、両方とも不完全かである。
<      ファイルは異なり、1 番目のファイルにだけこの行が含まれている。
>      ファイルは異なり、2 番目のファイルにだけこの行が含まれている。
(      1 番目のファイルにだけこの行が含まれているが、違いは無視される。
)      2 番目のファイルにだけこの行が含まれているが、違いは無視される。


サイト継続にご協力ありがとうございます。こちらの情報が何かのお役にたてれば幸いです。m(_ _)m

2010年11月12日金曜日

LinuxのシェルスクリプトでFTPする方法


LinuxのコマンドでFTPすることはもちろん可能ですが、
細かい内容はすぐ忘れてしまうのでシェルスクリプトにまとめてみました。

OS: CetnOS 5.7


■FTP用シェルスクリプトサンプル

#!/bin/sh

LOG="./log_ftp.log"
TARGET_HOST="192.168.216.232"
TARGET_USER="root"
TARGET_PASS="password"
TARGET_DIR="/tmp"
PUTDATA="putdata.txt"
GETDATA="getdata.txt"

uptime > $LOG

ftp -i -v -n $TARGET_HOST << END >> $LOG
user $TARGET_USER $TARGET_PASS
cd $TARGET_DIR
bin
# put $PUTDATA
# get $GETDATA
quit
END

uptime >> $LOG

exit 0

この情報が何かのお役にたてれば幸いです。m(_ _)m