вторник, 21 апреля 2009 г.

Bash_examples


MAN Bash:

http://poplinux.ru/adv-bash/part-3.html
http://ln.com.ua/~openxs/projects/man/solaris8/bash.html
http://citforum.ru/programming/shell/gl3.shtml
http://tldp.org/LDP/Bash-Beginners-Guide/html/Bash-Beginners-Guide.html#sect_09_04
http://ruslandh.narod.ru/howto_ru/Bash-Prog-Intro/Bash-Prog-Intro-7.html
MAN Vi:
http://wiki.firstvds.ru/index.php/%D0%A2%D0%B5%D0%BA%D1%81%D1%82%D0%BE%D0%B2%D1%8B%D0%B9_%D1%80%D0%B5%D0%B4%D0%B0%D0%BA%D1%82%D0%BE%D1%80_vim_-_%D0%BA%D1%80%D0%B0%D1%82%D0%BA%D0%BE%D0%B5_%D1%80%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%BE
Color PS1:
PS1="\[\033[0;33;40m[\t]\033 \[\033[1;31;40m[\033[1;32;40m\u@\h:\033[1;33;40m\w\033[1;31;40m]\033[1;35;40m $\033[0;37;0m\] "
( & )( ’ ' )( * )( [ ] ), ( ), { } )( ‘ ’, “ ”, « » )( / )( \ )( # )( § )( ~ )
амперсанд ( & )
апостроф ( ’ ' )
астериcк ( * )
скобки ( [ ], ( ), { } )
кавычки ( ‘ ’, “ ”, « » )
косая черта ( / )
обратная косая черта ( \ )
коммерческое at ( @ )
маркер списка ( • )
Циркумфлекс ( ^ )
октоторп/решётка/хеш ( # )
абзац ( ¶ )
знак параграфа ( § )
тильда ( ~ )

SCRIPTS :

1.Without empty lines:
egrep -v "^#|^$" /etc/squid/squid.conf
2.Switch register:
ls -al | awk '{print $9}' | tr [a-z] [A-Z]
3.All connection to 25 from one IP:
netstat -nt |grep ':25' |awk '{print $5}' |awk -F: '{print $1}' |sort -n |uniq |wc -l
4.Create random password:
head -c8 /dev/random | uuencode -m - | sed -n '2s/=*$//;2p'
5.Backup MySQL:
#!/bin/sh
WrkDir="/var/www/html"
BDir="/var/backup/new.name.kz"
User=root
Pass='pass'
Date=`date '+%Y-%m-%d'`
Subj="Web backup"
Mail='unixadmins@name.kz'
Bk="*.bcp"
DB_webs=(base_name)
Fs_webs=(dir_name)
if [ ! -d $BDir ]; then
mkdir $BDir
fi
find $BDir -type f -ctime +6 -exec rm -r "{}" ";"
cd ${WrkDir}
Count=${#DB_webs[*]}
/sbin/service httpd stop
for ((a=0; a < $Count; a++)); do /usr/bin/mysqldump -u${User} -p${Pass} ${DB_webs[$a]} > ${BDir}/${DB_webs[$a]}_${Date}.sql
/usr/bin/bzip2 ${BDir}/${DB_webs[$a]}_${Date}.sql
/bin/tar cpf - ${Fs_webs[$a]} | bzip2 -c > ${BDir}/${Fs_webs[$a]}_${Date}.tar.bz2
done
/sbin/service httpd start
cd ${BDir}
exit 0
6.File system report :
#!/bin/bash
# crontab - 15,45 * * * *
ReportDir=/usr/local/stat/report
Hostname=`hostname`
Mail='unixadmins@name.kz'
fs=(/) # df control
maxLimit=(90) # df control
TmpFile=file.tmp
Date=`date '+%Y-%m-%d'`
Hour=`date +%H`
Min=`date +%M`
if [ ! -d $ReportDir ]; then
mkdir $ReportDir
fi
if [ $Hour -eq 23 -a $Min -eq 45 ]; then
df -h | mail -s "df from server ${HOSTNAME}" $Mail
fi
cd $ReportDir
count=${#fs[@]}
df -h ${fs[*]} | sed -n '2,$p' | tr -d '\n' > $TmpFile
while read Line; do
FileSystem="`echo $Line | awk '{print $6}'`"
Use="`echo $Line | awk '{print substr ($5, 0, length($5)-1)}'`"
for ((a=0; a <>> ${TmpFile}.00
fi
fi
done
done < $TmpFile if [ -e "${TmpFile}.00" ];
then cat ${TmpFile}.00 | mail -s "Warning from server ${HOSTNAME}" $Mail rm ${TmpFile}.00
fi rm $TmpFile
exit 0
7.Collect statistics :
#! /bin/bash
ReportDir=/usr/local/stat/report
cd $ReportDir
echo ---------File Systems Utilization Statistics--------------------- > mon.list
df -h >> mon.list
echo ---------LASTLOG--------------------- >> mon.list
last -20 >> mon.list
echo ---------DIAGNOSTIC MESSAGES----- >> mon.list
tail -n 100 /var/log/messages >> mon.list
echo ---------DMESG MESSAGES---------- >> mon.list
dmesg | tail -n 60 >> mon.list
mailx -s WWW unixadmins@name.kz
exit 0
8.Copy local site to remoute host :
#!/bin/bash
WWW="/var/www/html"
DIR="/var/www/html/modules/general/"
BCKP="/var/backup/"
MAIL='unixadmins@name.kz'
mv $DIR/mysql.php $BCKP
cd $WWW
/bin/tar cfz $BCKP/site.tar.gz ./
mv $BCKP/mysql.php $DIR
cd $BCKP
/usr/bin/scp ./`ls -lhtr base_dump_name* | tail -1 | awk '{ print $9 }'` hosting@IP:/home/www
/usr/bin/scp ./site.tar.gz hosting@IP:/home/www
/usr/bin/ssh -l username IP "/home/www/sitecopy.sh" --->
#/home/www/sitecopy.sh :
##!/bin/bash
#cd /home/www
#tar xfz ./site.tar.gz
#bunzip2 ./base_dump_name*
#mysql -u user -ppass base_name < base_dump_name*
#rm -f ./base_dump_name*
#rm -f ./site.tar.gz
#chmod -R 755 /home/www/
#exit <---
if [ $? = 0 ];
then echo "WWW copy is OK" | mail -v $MAIL -s sitecopy
else echo "WWW copy looks NOT Good!" | mail -v $MAIL -s sitecopy
fi
rm -f $BCKP/site.tar.gz
exit 0
9.Copy to remoute :
#!/bin/sh
#sudo /etc/init.d/sendmail start;
BDir="/var/backup/new.name.kz";
Subj="WWW Backup to CVSLinux";
Mail='unixadmins@name.kz';
Data=`date '+%Y-%m-%d'`;
Report="/usr/local/stat/report/new.scp.file";
cd $BDir;
/usr/bin/scp *_${Data}* bcp@IP:/remout/dir/;
echo "=================BACKUP FILES================" > ${Report};
/usr/bin/ssh bcp@IP ls -l /remout/dir/ >> ${Report};
mailx -s "${Subj}" $Mail < ${Report} -v #&& sleep 5 && sudo /etc/init.d/sendmail stop exit 0
10.File renamer (simple)
#!/bin/bash
# renames.sh
# basic file renamer
criteria=$1
re_match=$2
replace=$3
for i in $( ls *$criteria* );
do
src=$i
tgt=$(echo $i | sed -e "s/$re_match/$replace/")
mv $src $tgt
done
11.Counter:
#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 10 ]; do
echo The counter is $COUNTER
let COUNTER=COUNTER+1
done
12.Counter:
#!/bin/bash
COUNTER=20
until [ $COUNTER -lt 10 ]; do
echo COUNTER $COUNTER
let COUNTER-=1
done
13.Counter:
#!/bin/bash
# calculate.sh
# basic file calculate
name=loop
total=0
#
for f in *
do
[ ! -f $f ] && continue
if grep $name $f > /dev/null
then
size=`cat $f | wc -c`
total=`expr $total + $size`
fi
done
echo "Total size of all files containing $name is $total"
14.File system monitor:
#!/bin/bash
count=$(df -h | sed 's/%//g'| grep '/.'| awk '{print $5}')
for i in $count
do
if [[ $i -ge 12 ]]
then
echo "ALARM!"
fi
done
15.Check type of directory:
#!/bin/bash
echo "Enter directory name: "
read directory
#
while [ "$directory" ]
do
if [ ! -d "$directory" ]
then
echo "$directory must be direcoty!"
echo "Please try again :"
read directory
continue
fi
#
if [ `ls $directory | wc -l` -gt 100 ]
then
echo "Directory: $directory is too large!"
break
fi
#
if [ `echo $?` = 0 ]
then
echo "You choose right directory!: $directory"
break
fi
done
16.
#!/bin/bash
# Must be present links
# ln -s /usr/local/bin/wh /usr/local/bin/wh-ripe
# ln -s /usr/local/bin/wh /usr/local/bin/wh-cw
# ln -s /usr/local/bin/wh /usr/local/bin/wh-radb
if [ -z "$1" ]
then
echo "Use like: `basename $0` [domain-name]"
exit 65
fi
case `basename $0` in
"wh" ) whois $1@whois.ripe.net;;
"wh-ripe") whois $1@whois.ripe.net;;
"wh-radb") whois $1@whois.radb.net;;
"wh-cw" ) whois $1@whois.cw.net;;
* ) echo "Use like: `basename $0` [domain-name]";;
esac
exit 0
17.Function, for
#!/bin/bash
backup_these_files()
{
for FILE_NAME in $*
do
cp $FILE_NAME /backup/
echo "$FILE_NAME has been backed up!"
done
}
backup_these_files *.conf
18.
#!/bin/bash
echo -n "Please enter [Y|yes] : "
read YN
case $YN in
[yY]|[yY][eE][sS]) ls -la
echo "You entered $YN"
;;
*)
echo "You did not enter [Y|yes]"
esac
19.
#!/bin/bash
while true
do
$0 &
done
exit 0
ALARM!!!
20.
#!/bin/bash
ROOT_UID=0
E_WRONG_USER=65
E_NOSUCHUSER=70
SUCCESS=0
if [ "$UID" -ne "$ROOT_UID" ]
then
echo; echo "Are you root ?"; echo
exit $E_WRONG_USER
else
echo; echo "Setting password for user...."
fi
username=bozo
NEWPASSWORD=security_violation
cat /etc/passwd | grep -q "$username"
if [ $? -ne $SUCCESS ]
then
echo "No such $username "
exit $E_NOSUCHUSER
fi
echo "$NEWPASSWORD" | passwd --stdin "$username"
echo "Set password for $username !"
echo "DONE!"
exit 0
21.
Create a perimeter file, like so:
touch -t yyyymmddHHMM marker_date
List files older than the marker_date:
find . -type f ! -newer marker_date -ls
Likewise, for a range of dates:
Create the perimeter files:
touch -t yyyymmddHHMM range_start
touch -t yyyymmddHHMM range_end
List the files between the range dates:
find . -type f -newer range_start ! -newer range_end -ls
22.
find . -name *song*abc2009*.jpg |
sed 's/\(^.*song.*\)abc2009\(.*.jpg\)$/mv "&" "\1def2010\2"/' | sh

22.
#!/bin/bash
username=root
password=***

instance_1_server=10.2.7.107
instance_2_server=10.2.7.108
instance_3_server=10.2.7.109

servers=("$instance_1_server" "$instance_2_server" "$instance_3_server" )
for I in `cat /home/zhakutove/files.txt`
do
 i=1
 for server in ${servers[@]}; do
   expect -c "
             # exp_internal 1 # uncomment for debugging
             spawn /usr/bin/scp $I $username@$server:$I
             expect {
               "*password:*" { send $password\r\n; interact }
               eof { exit }
             }
             exit
             "
   let "i=i+1"
 done
done
exit 0

23.
#Run commands from /root/useradd.sh
for server in ${servers[@]}; do
 i=1
        /usr/bin/ssh root@$server '/bin/bash -s' < /root/useradd.sh
 let "i=i+1"
done
24.

Комментариев нет: