RSS구독하기:SUBSCRIBE TO RSS FEED
즐겨찾기추가:ADD FAVORITE
글쓰기:POST
관리자:ADMINISTRATOR
'My Advanced Linux/Bash shell scripts'에 해당되는 글 6
본딩을 일일히 구성하는게 귀찮아진 나머지 스크립트를 짜려다, 혹시나 해서 검색해보니 좋은 스크립트가 있어서 소개!
출처는 맨 아래 적어놓았으며, 약간의 수정을 했다^^




#!/bin/sh
# This script creates bonding interfaces on RHEL 5.
#
# The first and second parameters are used to specify the enslaved interfaces.
# The third parameter is used to describe the name of the bonding interface.
# The network configuration is collected from the first device.
# After running the script please verify the/etc/modprobe.conf file as well as
# all/etc/sysconfig/network-scripts/ifcfg* files!
#
# LICENSE INFORMATION
#
# This software is released under the BSD license:
#
# Copyright 2010 Reiner Rottmann reiner[at]rottmann.it. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list
# of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or other
# materials provided with the distribution.
#
# 3. The name of the author may not be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Global variables

SCRIPTNAME=$(basename $0 .sh)

EXIT_SUCCESS=0
EXIT_FAILED=1
EXIT_ERROR=2
EXIT_BUG=10

VERSION="1.0.0"

# Base functions

# This function displays the basic usage
function usage {
echo "Usage: $SCRIPTNAME <first slave interface> <second slave interface> <bonding interface> <ipaddress> <netmask> <gateway>" >&2
echo "This script bonds two network interfaces on RHEL 5 with the static network config from the first slave interface." >&2
echo >&2
echo "e.g. # ./$SCRIPTNAME eth1 eth3 bond1 192.168.5.250 255.255.255.0 192.168.5.1" >&2
echo >&2
[[ $# -eq 1 ]] && exit $1 || exit $EXIT_FAILED
}

# This function checks that the command is run with the right parameters
function preflightcheck {

# This script needs to be run as root.
if [ $(id -u) -ne 0 ]; then
echo "You need to be root to run this script."
exit $EXIT_FAILED
fi

# Check if we have exactly 3 commandline parameters.

if [ $# -ne 6 ]; then
echo "Commandline parameter is missing. (only $# present)."
usage
exit $EXIT_FAILED
fi

# Check if the first input is correct.
if ! echo $1|grep -q "^eth[0-9]$"; then
echo "The first parameter needs to be an ethernet device (e.g. eth1)."
usage
exit $EXIT_FAILED
fi

# Check if the second input is correct.
if ! echo $2|grep -q "^eth[0-9]$"; then
echo "The second parameter needs to be an ethernet device (e.g. eth3)."
usage
exit $EXIT_FAILED
fi

# Check if the third input is correct.
if ! echo $3|grep -q "^bond[0-9]$"; then
echo "The third parameter needs to be a bonding device (e.g. bond3)."
usage
exit $EXIT_FAILED
fi
}

# The main function that creates the bonding devices.
function rh5mkbond {

# Load the bonding kernel module with active-backup mode and set mii link monitoring to 100 ms.
cp /etc/modprobe.conf /tmp/modprobe.conf.bonding
cat >> /tmp/modprobe.conf.bonding <<EOF
alias $3 bonding
EOF
cat /tmp/modprobe.conf.bonding|uniq > /etc/modprobe.conf


# Get interface details
#IP=$(/sbin/ifconfig $1|egrep -o "([0-9]{1,3}\.){3}[0-9]{1,3}"|sed -n "1p")
#NETMASK=$(/sbin/ifconfig $1|egrep -o "([0-9]{1,3}\.){3}[0-9]{1,3}"|sed -n "3p")
MACIF1=$(/sbin/ifconfig $1|egrep -o "([[:xdigit:]]{2}[:]){5}[[:xdigit:]]{2}")
MACIF2=$(/sbin/ifconfig $2|egrep -o "([[:xdigit:]]{2}[:]){5}[[:xdigit:]]{2}")


# Create the bond0 device file.
mv /etc/sysconfig/network-scripts/ifcfg-$3 /etc/sysconfig/network-scripts/ifcfg-$3.orig  2>/dev/null
cat >> /etc/sysconfig/network-scripts/ifcfg-$3 <<BOND
DEVICE=$3
BOOTPROTO=none
IPADDR=$4
NETMASK=$5
GATEWAY=$6
USERCTL=no
BONDING_OPTS="mode=0 miimon=100"
BOND


# Create the slave device files.
for i in $1 $2
do
mv  /etc/sysconfig/network-scripts/ifcfg-$i  /etc/sysconfig/network-scripts/ifcfg-$i.orig 2>/dev/null
cat >> /etc/sysconfig/network-scripts/ifcfg-$i <<IFS
DEVICE=$i
BOOTPROTO=none
HWADDR=$(/sbin/ifconfig $i|egrep -o "([[:xdigit:]]{2}[:]){5}[[:xdigit:]]{2}")
ONBOOT=yes
MASTER=$3
SLAVE=yes
USERCTL=no
IFS
done

}

# Call functions
preflightcheck $1 $2 $3 $4 $5 $6
rh5mkbond $1 $2 $3 $4 $5 $6

# End script

exit $EXIT_SUCCESS

linux 설치 후 DAEMON을 정리하기 귀찮아서 만든 쉘이라고 하기에도 민망한 스크립트 -_-;;

#!/bin/bash
# created by uzoogom at 2012.2.13

export LC_ALL=C

RED='\e[1;31m'
GREEN='\e[1;32m'
YELLOW='\e[1;33m'
BLUE='\e[1;34m'
NC='\e[0m'

chkall=$(chkconfig --list | egrep "(on|off)" | awk '{print $1}')
chkon=$(cat chklist.txt | egrep -v "^#")

# ALL DEAMON STOP
echo -e "ALL DEAMON STOP ========================================================="
for chkalloff in $chkall
do
chkconfig --level 2345 $chkalloff off
service $chkalloff stop 1>/dev/null
        echo -e "$chkalloff is ${RED}OFF${NC}"
done
echo "Done====================================================================="

echo ""

# SELECT DEAMON START
echo -e "SELECT DEAMON START ====================================================="
for chkselect in $chkon
do
chkconfig --level 2345 $chkselect on
service $chkselect start 1>/dev/null
echo -e "$chkselect is ${GREEN}ON${NC}"
done
echo "Done====================================================================="

echo ""

# selinux disabled
echo "selinux status==========================================================="
setenforce 0 1>/dev/null
perl -pi -e 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
grep "SELINUX=" /etc/selinux/config | egrep -v "^#"

참 조잡하다 = ㅂ=)a
그래도 유용하게 잘 돌아간다~

#!/bin/bash
# scripts by uzoogom

export LANG_ALL=ko_KR.eucKR
day=$(date +%Y-%m-%d)
backuplist=$(cd /backup/ && ls -d *)
list="$day"backup_check.txt

echo "$day backup status" > $list
echo " " >> $list
echo "Success list--------------------------------" >> $list

echo " " > bad.txt
echo "Fail list--------------------------------" >> bad.txt

for checkname in $backuplist
do
        check=$(find /backup/$checkname -type f -name "backupTime($day).txt" | wc -l )

        if [ $check == 1 ]
        then
                echo "$checkname backup is successfully Done!" >> $list
        else
                echo "$checkname backup is Fail. plz check your system." >> bad.txt
        fi

done
cat bad.txt >> $list
success=$(grep "successfully" $list | wc -l)
nonsuccess=$(grep "Fail" $list | wc -l)
sed "1a Success  :"$success"\nFailure:"$nonsuccess"" $list > last.txt
cat last.txt > $list
cat $list | mail -s ""$day" real server backup status" uzoogom@dunet.co.kr serverbin@dunet.co.kr
mv $list /root/SH/checklog
rm -f /root/backup/*.txt
안타깝게도 CPU 타잎 확인 하는 부분은 제대로 계산이 안된다.
이유는 쿼드코어, 코어2듀오, 듀얼코어, 하이퍼스레딩 등 때문에...
사실 좀 더 세밀하게 짜면 정상적으로 할 수있는데 귀찮아서..........

#!/bin/bash
LANG=C
unset GREP_OPTIONS GREP_COLOR

echo "
################################ SYSTEM CHECK uzoogom edition. ################################

1) Network Information-------------------------------------------------------------------------
1-1) HOSTNAME: `hostname`

1-2) Ethernet Information
`ifconfig | grep -v "127.0.0.1" | grep "addr"`

1-3) Route(gateway) Information
`route | egrep '(default|Gateway)'`


2) SYSTEM Information-------------------------------------------------------------------------
2-1)CPU Information
CPU : `cat /proc/cpuinfo | grep "processor" | wc -l` EA
`cat /proc/cpuinfo | grep "model name" | uniq`
`cat /proc/cpuinfo | grep "MHz" | uniq`

2-2) Memory Information
`free -m`

2-3) Partition Information
`fdisk -l | grep dev`

2-4) Disk Information
`df -h`


3) PROCESS Information-------------------------------------------------------------------------
`pstree`


4) Open Port Scanning-------------------------------------------------------------------------
`netstat -antp | egrep '(LISTEN|Address)'`


5) Auto start processor-------------------------------------------------------------------------
5-1) Crontab
`crontab -l`

5-2) chkconfig list
`chkconfig --list | grep "3:on"`

5-3) rc.local
`egrep -v "(#|touch)" /etc/rc.local`
"
후리켓  | 2009.10.08 16:06 신고
테스트 패치ㅋ

--- test.sh.ori 2009-10-08 06:55:51.000000000 +0900
+++ test.sh 2009-10-08 06:55:27.000000000 +0900
@@ -2,6 +2,10 @@
LANG=C
unset GREP_OPTIONS GREP_COLOR

+if [ ! $LOGNAME = root ] && [ ! $UID = 0 ];then
+ exit
+fi
+
echo "
################################ SYSTEM CHECK uzoogom edition. ################################
요즘에 회사에서 써먹을려고 다시 짠 백업 스크립트
행여나 이 블로그에 흘러들어와서 그걸 그대로 쓴다면 무궁무진한 오류가 뜨니 주의하시요!

#!/bin/bash
#edit by uzoogom 090723
#
# backup configure
host=$(hostname)
day=$(date +%Y-%m-%d)
check=$(mount | grep -c "backup")

# Backup Storage Mounting Check
if [ $check == 1 ]
        then
                echo "Backup Storage Mounting Check .... OK!!"
        else
                echo "Backup Storage Mounting Check .... FAIL!!"
                echo "Exit backup scripts"
                exit 0
fi

# Make a backup Directory
mkdir -p /backup/${host}/{webdata,data,config} 2>/dev/null
mkdir /root/backup/reference 2>/dev/null

# 백업 할 디렉토리를 적을 파일 생성

touch /root/backup/reference/{webdir,datadir,configfile}

# Lists to Backup 백업 할 디렉토리를 적을 파일 생성
WEBDATA=$(grep -v "^#" /root/backup/reference/webdir)
DATA=$(grep -v "^#" /root/backup/reference/datadir)
CONFIG=$(grep -v "^#" /root/backup/reference/configfile)

# TMP Directory
LIST="/tmp/backuplist_$$.txt"

# Target Backup Locations
WEBDATABACKUP="/backup/${host}/webdata"
DATABACKUP="/backup/${host}/data"
CONFIGBACKUP="/backup/${host}/config"
DATABASEBACKUP="/backup/${host}/database"

#
echo "
========================================================================
Starting backup at `date +%Y-%m-%d\ %H:%M:%S`
========================================================================
"

# date to nubmer 증분 백업을 위해서 날자 지정
# 1-Mon, 2-Tue, 3-Wed, 4-Thu, 5-Fri, 6-Sat, 7-Sun
set $(date '+%u')

# backup Time stamp
rm -f /backup/${host}/backupTime*.txt
echo Starting at `date +%Y-%m-%d\ %H:%M:%S` > "/backup/${host}/backupTime($day).txt"

if test "$1" = "6" ;
then
        # weekly a full backup of all data and config. settings:
        #
        echo "Step1. Performing Full Data Backup--------------------------------------"
        tar zcf "$DATABACKUP/data_full_$day.tgz" $DATA 2>/dev/null

        echo "Removing incremental data backups..."
        rm -f $DATABACKUP/data_diff*

        echo "Removing four week old full Data backup..."
        find $DATABACKUP -depth -type f \( -ctime +20 -o -mtime +20 \) -print > $LIST
        rm -f `cat $LIST`
        echo "------------------------------------------------------------------Done +"
        echo ""

        #
        echo "Step2. Performing Full WebData Backup-----------------------------------"
        tar zcf "$WEBDATABACKUP/webdata_full_$day.tgz" --exclude-from=./reference/exclude  $WEBDATA 2>/dev/null

        echo "Removing incremental data backups..."
        rm -f $WEBDATABACKUP/webdata_diff*

        echo "Removing four week old full WebData backup..."
        find $WEBDATABACKUP -depth -type f \( -ctime +20 -o -mtime +20 \) -print > $LIST
        rm -f `cat $LIST`
        echo "------------------------------------------------------------------Done +"
        echo ""

        #
        echo ""
        echo "Step3. Performing Full Config Backup------------------------------------"
        tar zcf "$CONFIGBACKUP/config_full_$day.tgz" $CONFIG 2>/dev/null

        echo "Removing incremental config backups..."
        rm -f $CONFIGBACKUP/config_diff*

        echo "Removing four week old full config backup..."
        find $CONFIGBACKUP -depth -type f \( -ctime +20 -o -mtime +20 \) -print > $LIST
        rm -f `cat $LIST`
        echo "------------------------------------------------------------------Done +"
else
        # incremental data backup:
        #
        echo "Step1. Performing Incremental Data Backup-------------------------------"
        find $DATA -depth -type f \( -ctime -1 -o -mtime -1 \) -print > $LIST
        tar zcfT "$DATABACKUP/data_diff_$day.tgz" "$LIST" 2>/dev/null
        rm -f "$LIST"
        echo "------------------------------------------------------------------Done +"
        echo ""

        # incremental webdata backup:
        #
    echo "Step2. Performing Incremental WebData Backup----------------------------"
        find $WEBDATA -depth -type f \( -ctime -1 -o -mtime -1 \) -print > $LIST
        tar zcfT "$WEBDATABACKUP/webdata_diff_$day.tgz" --exclude-from=./reference/exclude "$LIST" 2>/dev/null
        rm -f "$LIST"
        echo "------------------------------------------------------------------Done +"
        echo ""

        # incremental config backup:
        #
        echo "Step3. Performing Incremental Config Backup-----------------------------"
        find $CONFIG -depth -type f  \( -ctime -1 -o -mtime -1 \) -print > $LIST
        tar zcfT "$CONFIGBACKUP/config_diff_$day.tgz" "$LIST" 2>/dev/null
        rm -f "$LIST"
        echo "------------------------------------------------------------------Done +"
fi

# MySql 용 백업 설정이나, MySql을 마땅히 백업할 서버가 없어서 주석처리
# Database Backup
#
#mkdir -p /backup/${host}/database 2>/dev/null
#DB_DIR="/usr/local/mysql/data"
#
# Create SQL dump of databases and compress:
#echo "
#Archiving Databases...
#"
# Find current databases
# DB=( $(find ${DB_DIR}/ -maxdepth 1 -type d ! -name ".*" | sort | sed -e 's/\/usr\/local\/mysql\/data\///g') )
# Set for loop max counter based on number of databases
# j=${#DB[@]}
# for (( i=0; i&lt;j; i++ )); do
#         mysqldump -u user --password=passwd --opt ${DB[i]} | gzip >"$DATABASEBACKUP/${DB[i]}_$day.sql.gz"
# done
#
#echo "
#Removing two week old database backups...
#"
#find $DATABASEBACKUP -depth -type f \( -ctime +13 -o -mtime +13 \) -print > $LIST
#rm -f `cat $LIST`
#rm -f "$LIST"
#

# backup Time stamp
echo Finished at `date +%Y-%m-%d\ %H:%M:%S` >> "/backup/${host}/backupTime($day).txt"
echo "
========================================================================
Finished: `date +%Y-%m-%d\ %H:%M:%S`
========================================================================
"
exit 0
모든 스크립트의 기본은 정말이지 단순하다.
얼마나 그 명령어에 대해 이해를 하고 있느냐.
단지 그것 뿐이다.

여기에서는 가장 기본적으로 그 해당 명령어를 사용하는 방법은 알고 있으리라 생각하고 적는다.
괜시리 명령어 사용법도 모르면서 스크립트에 덤벼들지 마라. 잘못하면 시원하게 파일을 날릴 수 있으니까!

어찌보면 가장 단순하지만, 가공할만한 잠재력을 가진 명령어 중 하나인 find!
find만 잘 응용해도 열 스크립트 안 부럽다!


1. 특정 파일 속 특정 단어 찾기
ex) html 파일에서 mms:// 찾기
find . -type f -name "*.html" -exec grep "mms://" {} /dev/null \;
(뒤에 /dev/null을 붙이는 이유는 해당 파일명을 보기 위함이다.)

2. 특정 파일 속 특정 단어 바꾸기
ex) html 파일에서 mms://를 http://로 바꾸기
find . -type f -name "*.html" -exec perl -pi -e 's/mms/http/g' {} \;
(유의 할 점은 특수기호[가령 / 같은..]는 인식을 못하기 때문에 문자로 쓰기 위해선 꼭 \를 붙여줘야한다)

3. 특정 파일만 압축하기
ex) html 파일만 찾아서 압축하기
for i in $(find . -name '*.html'); do tar -zrvf html.tgz $i; done

4. 5일 지난 파일 삭제하기
rm -f 'find . -mtime +5'

뭐 기본적으로 이정도만 응용해도 꽤나 훌륭한 결과를 얻을 수 있다.



우주곰:지구곰이 아닙니다.
지구곰이 아닙니다.
Categories (190)
Information (5)
About uzoogom (5)
My Advanced Linux (73)
Learning Linux (96)
OperatingSystem (5)
Databases (4)
Tips! (1)
OpenSource (1)
«   2018/01   »
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      
  1. 2012/12 (2)
  2. 2012/04 (3)
  3. 2012/03 (6)
  4. 2012/02 (6)
  5. 2012/01 (2)