Category Archives: SHELL SCRIPT

STARTUP SCRIPT WHEN USER LOGIN SHELL


Private Configuration

[root@alfamart ~]# vim /${USER}/.bashrc

echo “while sleep 1;do echo -ne ’33]2;’$USER@$HOSTNAME’ ‘$(uptime)’07’;done &” >> /${USER}/.bashrc

Global Configuration

[root@alfamart ~]# vim /etc/bashrc

echo “while sleep 1;do echo -ne ’33]2;’$USER@$HOSTNAME’ ‘$(uptime)’07’;done &” >> /etc/bashrc

Thanks You

 

PERL + Threads ping multiple host


#!/usr/local/bin/perl
use Net::Ping;
use threads;
use Time::HiRes qw(sleep usleep);
use Log::Log4perl;
use threads::shared;

my $shr_var : shared = 0;

my $log_conf = “/etc/log4perl.conf”;
Log::Log4perl::init($log_conf);
my $logger = Log::Log4perl->get_logger();

my @hosts = (‘192.168.0.1’, ‘192.168.0.2’, ‘192.168.0.3’, ‘192.168.0.4’, ‘192.168.0.5’, ‘192.168.0.6’, ‘192.168.0.7’);

for ($ip=0; $ip<=$#hosts; $ip++){
threads->create(\&pingHost,$hosts[$ip]);
}

while(1) {
#print “Main is running\n”;
sleep(1);
}

exit 0;

sub pingHost{
my $host = $_[0];
my $timeout = 1;
my $cnt = 0;
my $pinger = Net::Ping->new(‘icmp’, $timeout);

while ($shr_var < 1) {
$cnt++;

if (!$pinger->ping($host)) {
$logger->error(“$host IS DOWN”);
}
sleep(1);
}

$pinger->close();
}

—————————————————–

[root@alfamart ping-perl]# more log4perl.conf
###############################################################################
## Log::Log4perl Conf #
################################################################################
log4perl.rootLogger = DEBUG, LOG1
log4perl.appender.LOG1 = Log::Log4perl::Appender::File
log4perl.appender.LOG1.filename = /home/moses/log/ping.log
log4perl.appender.LOG1.mode = append
log4perl.appender.LOG1.layout = Log::Log4perl::Layout::PatternLayout
log4perl.appender.LOG1.layout.ConversionPattern = %d %p %m %n

 

Linux Memory Calculation


free -m => FALSE

Formula :

(used-buffers-cached)/total * 100%

#!/bin/bash
 free -m | grep "Mem:" | cut -f2 -d:|sed 's/\([0-9]\) /\1\,/g' | sed -e 's/[\t ]//g;/^$/d' | while read array; do \
 used=`echo $array | cut -d',' -f2`
 buffers=`echo $array | cut -d',' -f5`
 cached=`echo $array | cut -d',' -f6`
 total=`echo $array | cut -d',' -f1`
 HASIL=`echo - | awk '{ print '$((used-buffers-cached))'/'$total'}'`
 echo `printf "Usage Memory = %.2f" $HASIL`"%";
 done

by moses

Shell Script Division,Subtraction,Addition


Floating Point Division
X=2
Y=4
echo - | awk '{ print '$X'/'$Y'}'
Subtraction on Shell Script
X=2
Y=4
echo $((X-Y))
Float Shell Script
X=100
printf "%.2f\n" $X
Addition on Shell Script
X=1 Y=2 Z=3
echo $((X+Y+Z))
Remove Space On Shell Script
X="1 2 3 4 5"
echo $X | sed -e 's/[\t ]//g;/^$/d'

Check Service MYSQL using Xinet.d , Telnet Service MYSQL


[root@svrrepo html]# vim /opt/mysqlchk

#!/bin/bash
MYSQL_HOST=”localhost”
MYSQL_PORT=”3306″
MYSQL_USERNAME=”root”
MYSQL_PASSWORD=”passowordku”

TMP_FILE=”/tmp/mysqlchk.out”
ERR_FILE=”/tmp/mysqlchk.err”

/usr/bin/mysql –host=$MYSQL_HOST –port=$MYSQL_PORT –user=$MYSQL_USERNAME \
–password=$MYSQL_PASSWORD -e”show databases;” > /dev/null
RETVAL=$?

if [ “${RETVAL}” -eq “0” ]
then
# mysql is fine, return http 200
/bin/echo -e “HTTP/1.1 200 OK\r\n”
/bin/echo -e “Content-Type: Content-Type: text/plain\r\n”
/bin/echo -e “\r\n”
/bin/echo -e “MySQL is running.\r\n”
/bin/echo -e “\r\n”
else
# mysql is fine, return http 503
/bin/echo -e “HTTP/1.1 503 Service Unavailable\r\n”
/bin/echo -e “Content-Type: Content-Type: text/plain\r\n”
/bin/echo -e “\r\n”
/bin/echo -e “MySQL is *down*.\r\n”
/bin/echo -e “\r\n”
fi

save wq!

[root@svrrepo html]# vim /etc/xinetd.d/mysqlchk

# /etc/xinetd.d/mysqlchk
# default: on
# description: mysqlchk
service mysqlchk
{
flags = REUSE
socket_type = stream
port = 9200
wait = no
user = nobody
server = /opt/mysqlchk
log_on_failure += USERID
disable = no
only_from = 0.0.0.0/0 # recommended to put the IPs that need
# to connect exclusively (security purposes)
per_source = UNLIMITED # Recently added (May 20, 2010)
# Prevents the system from complaining
# about having too many connections open from
# the same IP. More info:
# http://www.linuxfocus.org/English/November2000/article175.shtml
}

save wq!

[root@svrrepo html]# vim /etc/services
#wap-wsp 9200/tcp # WAP connectionless session service
mysqlchk 9200/tcp
wap-wsp 9200/udp # WAP connectionless session service

save wq!

[root@svrrepo html]# /etc/init.d/xinetd restart
Stopping xinetd: [ OK ]
Starting xinetd: [ OK ]

[root@svrrepo html]# telnet 192.168.0.253 9022
Trying 192.168.0.253…
telnet: connect to address 192.168.0.253: Connection refused
[root@svrrepo html]# telnet 192.168.0.253 9200
Trying 192.168.0.253…
Connected to 192.168.0.253.
Escape character is ‘^]’.
HTTP/1.1 200 OK

Content-Type: Content-Type: text/plain

MySQL is running.

Connection closed by foreign host.

HOW BACKUP EVERY TABLE USING SHELL SCRIPT


Berikut adalah sedikit shell script untuk melakukan backup per table dari suatu database. Cocoknya script ini dijalankan di single server (tidak memiliki server backup), namun pada script ini juga dibuat satu parameter sehingga bisa di backup di ke server backup dalam bentuk text file (.sql) dan dimport ke server backup.

Kelemahan dari backup ini adalah : Backup tidak dilakukan secara realtime, tapi H-1. Jadi ketika database corrupt & hardisk server crash data terakhir adalah H-1

#!/bin/bash
#A UNIX / Linux shell script to backup per table!!!!!
# ————————————————————————-
# Copyright (c) 2011 Mustafa Tambunan <mustafa@intelix.co.id>
# Created : 2011-12-23 03:00:00
# ————————————————————————-
# Tested under RHEL / CentOS 5.5
# note :
# Jalankan di crontab setiap jam 1 pagi : contoh : 0 1 * * * /shell/filename.sh > /dev/null

#IP DARI SERVER UTAMA
_SRC_HOST=”192.168.137.100″
_SRC_USER=”ecentrix”
_SRC_PASSWD=”mosespassword”
_SRC_OPT=” –no-create-info –compact –skip-quote-names”
_SRC_DBNAME=”ecentrix_addons” # nama datbase di server utama

#IP/LOCALHOST DARI SERVER BACKUP
_DEST_HOST=”localhost”
_DEST_USER=”ecentrix”
_DEST_PASSWD=”mosespassword”
_DEST_DBNAME=”ecentrix_addons” #nama database di server backup

_BACKUP_IS_AVAILABLE=”N”

_CMD_MYSQLDUMP=”$(which mysqldump)”
_CMD_MYSQL=”$(which mysql)”

if [ $1 != “” ]; then
_DATE=$1
else
_DATE=$(date –date=”1 days ago” +”%Y-%m-%d”)
fi

exit
_DIR_SQL_DATA=”/home/ecentrix/backup_db/${_SRC_DBNAME}/${_DATE}”
_LOG_DIR=”/home/ecentrix/backup_db/${_SRC_DBNAME}/log/”

mkdir -p ${_DIR_SQL_DATA}
mkdir -p ${_LOG_DIR}

#cat > ${_LOG_DIR}”${_DATE}.log”

_logger(){
LOG_FORMAT=” [ “$( date +’%H:%M:%S’)”] ”
echo $LOG_FORMAT $1
echo $LOG_FORMAT $1 >> ${_LOG_DIR}”${_DATE}.log”
}

_ARR_TABLE=(
“table_name” “field_param”
“dashboard_user” “created_time”
“dashboard_user_privilege” “created_time”
“ecentrix_sms_in” “receive_date”
“ecentrix_sms_out” “send_date”
“ecentrix_sms_call” “created_time”
“ecentrix_fax” “created_time”
“ecentrix_voice_mail” “created_time”
“ecentrix_blocked_caller” “created_time”
“ecentrix_fax” “created_time”
“pp_fax” “created_time”
“pz_fax” “created_time”
“pz_sms_out” “created_time”
)

_COUNT_ARR_TABLE=13
_LIMIT_TBL_NAME=$((($_COUNT_ARR_TABLE*2)-4))

_TBL_NAME=0
_TBL_PARAM=1
_C=2

while [ ${_TBL_NAME} -le ${_LIMIT_TBL_NAME} ] ; do
_TBL_NAME=$( expr ${_TBL_NAME} + ${_C} )
_TBL_PARAM=$( expr ${_TBL_PARAM} + ${_C} )

if [ “${_ARR_TABLE[${_TBL_PARAM}]}” == “” ]; then
_WHERE=” ”
else
_WHERE=” –where=date(${_ARR_TABLE[${_TBL_PARAM}]})=’${_DATE}'”
fi

#_logger ${_WHERE}
#dump to text file then import to database backup every day
${_CMD_MYSQLDUMP} -h ${_SRC_HOST} -u${_SRC_USER} -p${_SRC_PASSWD} ${_SRC_OPT} ${_SRC_DBNAME} ${_ARR_TABLE[${_TBL_NAME}]} ${_WHERE} | replace “INSERT
INTO” “INSERT IGNORE INTO “> ${_DIR_SQL_DATA}/${_ARR_TABLE[${_TBL_NAME}]}”.sql”
if [ “$?” -eq 0 ];then
_TBL_SIZE=$(ls -lah ${_DIR_SQL_DATA}/${_ARR_TABLE[${_TBL_NAME}]}.sql | awk ‘{ print $5}’)
_logger “Success, dump table ${_ARR_TABLE[${_TBL_NAME}]} with file size = ${_TBL_SIZE}”
if [ “${_BACKUP_IS_AVAILABLE}” == “Y” ]; then
if [[ -f ${_DIR_SQL_DATA}/${_ARR_TABLE[${_TBL_NAME}]}.sql && ${_TBL_SIZE} > 0 ]]; then
#start import to database backup
${_CMD_MYSQL} -h ${_DEST_HOST} -u${_DEST_USER} -p${_DEST_PASSWD} –database ${_DEST_DBNAME} < ${_DIR_SQL_DATA}/${_ARR_TABLE[$
{_TBL_NAME}]}”.sql”
if [ “$?” -eq 0 ];then
_logger “Success, import table ${_ARR_TABLE[${_TBL_NAME}]}”
else
_logger “Fail, import table ${_ARR_TABLE[${_TBL_NAME}]}”
fi
#edn import to backup
else
_logger “Not import table ${_ARR_TABLE[${_TBL_NAME}]} bcz size = 0 or file not exits”
fi
fi
else
_logger “Fail, dump table ${_ARR_TABLE[${_TBL_NAME}]}”
fi
done

#dump lates schema database ecentrix every month
_DATE_LAST_MONTH=”$( date +%Y-%m)-“`cal $( date +%m) $( date +%Y) |tail -2|awk ‘{print $NF;exit}’`
if [ “$( date +%F )” == “${_DATE_LAST_MONTH}” ]; then
${_CMD_MYSQLDUMP} -h ${_SRC_HOST} -u${_SRC_USER} -p${_SRC_PASSWD} -d –quick –database ${_SRC_DBNAME} | gzip -c > ${_DIR_SQL_DATA}/${_SRC_DBNAME}-d
b-schema.sql.gz
fi

cat > ${_LOG_DIR}fail.log
egrep -wRZ “Fail” ${_LOG_DIR} >> ${_LOG_DIR}fail.log

Jika harus dibackup ke server backup maka rubah parameter:

_BACKUP_IS_AVAILABLE=”Y”

dan sesuaikan parameter

#IP DARI SERVER UTAMA
_SRC_HOST=”192.168.137.100″
_SRC_USER=”ecentrix”
_SRC_PASSWD=”mosespassword”
_SRC_OPT=” –no-create-info –compact –skip-quote-names”
_SRC_DBNAME=”ecentrix_addons” # nama datbase di server utama

#IP/LOCALHOST DARI SERVER BACKUP
_DEST_HOST=”localhost”
_DEST_USER=”ecentrix”
_DEST_PASSWD=”mosespassword”
_DEST_DBNAME=”ecentrix_addons” #nama database di server backup

 

Terimakasih

 

 

REPLACE STRING IN MULTIPLE FILE ON DIRECTORY


Berikut adalah sedikit shell script untuk me-replace string di beberapa file or directory.

[root@node1 sort]# vim replaceString.sh
#!/bin/bash

writeLog(){
        LOG="/tmp/logReplaceString-$( date +%F)"
        echo $1
        echo [ $(date +%r) ] $1 >> $LOG
}

replaceString(){
LOG="/tmp/replaceString-$( date +%F)"
        if [ $# -ne 3 ]; then
                writeLog ""
                writeLog "---------------------------------------------------------------------------"
                writeLog "Wrong parameter!!!"
                writeLog "Format Parameter : [Full Path Directory] [TEXT TO SEARCH] [TEXT TO REPLACE]"
                writeLog "Example          : /home/ecentrix/cfg/ centrix gmosecentrix"
                writeLog "---------------------------------------------------------------------------"
        else
                if [ -d "$1" ] || [ -f "$1" ];then
                        egrep -wlRZ "$2" $1 | xargs -0 -l sed -i -e "s/$2/$3/g"
                        writeLog ""
                        writeLog "-------------------------------------------------------------------"
                        writeLog "Replace word $2 to $3 on directory $1"
                        writeLog "-------------------------------------------------------------------"
                        writeLog ""
                else
                        writeLog $1 " is not file or directory"
                fi
        fi
}

replaceString $1 $2 $3

Cara penggunaan:
[root@node1 sort]# sh /home/ecentrix/sort/replaceString.sh /home/ecentrix/cfg/ ecentrix gmosecentrix
artinya setiap kata "ecentrix" yang ditemukan di directory "/home/ecentrix/cfg" akan di replace dengan kata
gmosecentrix"
Biasanya ini digunakan untuk pergantian IP atau password di file2 configurasi atau di file2 php
atau bisa di buat di cronta
[root@node1 sort]# crontab -l
59 23 * * * /home/ecentrix/sort/replaceString.sh /home/ecentrix/cfg/ 172.10.10.0 172.10.10.10
59 23 * * * /home/ecentrix/sort/replaceString.sh /home/ecentrix/cfg/ ecentrix new-ecentrix

Semoga bermanfaat :)
shisdew

Listens until think alike

moses.spaceku@yahoo.com / voip ipbx

Hosted PBX, IP-PBX SOHO/ CALL CENTER, VOICE GATEWAY, VOICE CARD, COST EFECTIVE SOLUTIONS (LCR), GSM/CDMA GATEWAY

%d bloggers like this: