最後更新: 2018-09-17
目錄
- Wake-up drac 的 HW watchdog
- Get NIC 's IP
- ftp script
- Confirm run script
- Loop Program
- ...
- mysql script template
- daily backup report (rsnapshot)
- rsync folder
Wake-up drac 的 HW watchdog
wake-up-dog.sh
#!/bin/bash
/opt/dell/srvadmin/bin/idracadm getsysinfo -w
cron jobs
# wake-up hw watchdog * * * * * /root/scripts/wake-up-dog.sh
Get NIC 's IP
# IP with Subnet
nic=eth0 ifconfig=/sbin/ifconfig # cron job 裡未必可以直接行 ifconfig ip=$($ifconfig $nic | awk '/inet / {print $2}') echo $ip
# IP
ip addr show eth0 | awk '/inet /{sub(/\/24/,"",$2); print $2}'
ftp_script
ftp cli script
script.cmd:
open ftp.domain.com user mylogin mypasswd lcd /my/local/dir put myfile bye quit
Run Script
ftp -inv < script.cmd &
Single Line Command
#!/bin/bash #### Setting #### host=x.x.x.x id=xxxx pw=yyyy filename=test.txt remodir=/upload log=logfile.log #### CODE #### ftp -n "$host" > $log 2>&1 <<EOC user $id $pw binary cd $remodir put $filename bye EOC
Check RAID Healt
chkraid.sh
#!/bin/bash _ADMIN=xxx@xxx /opt/MegaRAID/MegaCli/MegaCli64 PDList -aALL | grep Firmware > /tmp/raid_status.txt echo "" | mailx -s"vpshost RAID status" -a /tmp/raid_status.txt $_ADMIN
chklib.sh
#!/bin/bash _MYNAME="chklib.sh" _CALLER=`basename $0` ######## CODE ######## chklib(){ if [ x"$_CALLER" == x"$_MYNAME" ] then echo "It is a library. Please source it." exit fi } chklib
Lock File
lock.sh
#!/bin/bash # File: lock.sh @ 20160519 _MYNAME="lock.sh" _CALLER=`basename $0` _LOCKPERIOD=20 _LOCKFILE="/tmp/$_CALLER.lock" ######## CODE ######## chklib(){ if [ x"$_CALLER" == x"$_MYNAME" ] then echo "It is a library. Please source it." exit fi } chklib # lock timeout value if [[ -z $_MYLOCKPERIOD ]]; then _LOCKPERIOD=300 else _LOCKPERIOD=$_MYLOCKPERIOD fi echo "LOCKPERIOD: $_LOCKPERIOD" punlock() { rm $_LOCKFILE && echo "UNLOOKED" return 0 } plock() { if [ ! -f $_LOCKFILE ]; then _LOCKTIME=`date +%s` echo $_LOCKTIME > $_LOCKFILE && echo "LOOKED" return 0 else _LOCKTIME=`cat $_LOCKFILE` _CURTIME=`date +%s` _WAITTIME=$(( $_CURTIME - $_LOCKTIME )) echo $_CURTIME "-" $_LOCKTIME "= "$_WAITTIME"($_LOCKPERIOD)" if [[ $_WAITTIME -gt $_LOCKPERIOD ]]; then echo "Lock timeout: $_WAITTIME" punlock return 0 else echo "Locking" exit fi fi } #####################
Usage
#!/bin/bash export _MYLOCKPERIOD=30 source /root/bash_script/lock/lock.sh plock echo "doing" punlock
Kill a process script
#!/bin/bash _PNAME="java" _SNAME="myscript.jar" list=$(pidof $_PNAME) for p in $list do echo "Checking $p" ps ax | grep $p | grep $_SNAME &> /dev/null if [[ $? -eq 0 ]] then echo "Killing $p..." #kill -TERM $p fi done
loop provent "newline, space"
user.txt
userA userB userD userE
useful.sh
#!/bin/bash
while read line
do
# 防空格空行
_linecheck=`echo $line | wc -w`
if [ $_linecheck == 1 ]
then
.....
fi
done < "user.txt"
Batch Change Password
resetpw.sh
#!/bin/bash pw='????????' for i in `cat userlist.txt` ; do username="`echo $i | cut -d':' -f 1`" userpwpair="`echo $username':'$pw`" echo $userpwpair | chpasswd done
check running user
#!/bin/bash RUN_USER="dbbackup" cur_user=`whoami` if [ $cur_user != $RUN_USER ] then echo "Please run it: " echo "sudo -u $RUN_USER /backup/dbbackup/baksh.sh" && exit 1 fi
Run script as another user
#!/bin/bash whoami sudo -u someuser bash << EOF echo "In" whoami EOF echo "Out" whoami
Check user exist
#!/bin/bash RUN_USER="dbbackup" result=`getent passwd $RUN_USER` if [ x$result = x"" ] then echo "User $RUN_USER no exist" fi
User Personal FTP A/C
#!/bin/bash _CONFIGFILE=/root/tmp/httpd.conf _TMPCONFIG=/tmp/addftpuser.tmp _MARKER='#personal_ftp_user#' _USER=$1 _WEBUSR="????" _WEBPW="????" # check username if [[ -z "$_USER" ]]; then echo "Please input username" exit fi # prepare configure file cat > $_TMPCONFIG << EOF ############################################# Alias /$_USER/ /home/$_USER/webftp/ <Directory "/home/$_USER/webftp/"> <Files ~ "\.(php|htm|html)$"> deny from all </Files> allow from all Options None AllowOverride None AuthType Basic AuthName "Restricted Area" AuthBasicProvider file AuthUserFile /home/$_USER/webftp.pw AuthGroupFile /dev/null Require valid-user </Directory> EOF # backup configure cp -f $_CONFIGFILE $_CONFIGFILE.bak # modify configure sed -i "/$_MARKER/r $_TMPCONFIG" $_CONFIGFILE # Folder for web mkdir /home/$_USER/webftp chown $_USER /home/$_USER/webftp # Web Folder Login htpasswd -b -c /home/$_USER/webftp.pw $_WEBUSR $_WEBPW # Cleanup rm $_TMPCONFIG # Test apache apachectl -t
response_watchdog.sh
#!/bin/bash pidfile="/var/run/response/lmtpd.pid" prog="/root/scripts/response.sh" function checkpid { if [ -f $pidfile ]; then pid=`cat $pidfile` kill -0 $pid &> /dev/null if [ $? != 0 ]; then echo "program crash, start new one" rm $pidfile bash $prog else echo "porgram working fine" fi else echo "without pid file, start new one" bash $prog fi sleep 1 } checkpid
Check Disk Usage
CheckDiskUsage.sh
#!/bin/bash # Unit: G _LUsage=100 _CheckPartition="/" _HOSTNAME="??????????" _ADMIN="???@???" _EMAIL="???@???" ########################################################### sendmail(){ echo $_MSG | mail -r $_EMAIL -s"Over Disk Usage" \ -a /tmp/checkdiskusage.txt $_ADMIN } _MSG="$_HOSTNAME over disk usage, Limit: $_LUsage G" df -h > /tmp/checkdiskusage.txt echo "\$6 == \"$_CheckPartition\" { print \$3 }" > /tmp/prog.txt _usage=`awk -f /tmp/prog.txt /tmp/checkdiskusage.txt` echo $_usage | grep G > /dev/null if [[ $? -eq 0 ]]; then _usage=`echo $_usage | sed 's/G//g'` if [[ $(echo "$_usage > $_LUsage" |bc ) -eq 1 ]]; then echo "Over Usage" sendmail fi fi
Cron Job
# daily check disk usage 3 3 * * * /root/scripts/checkdiskusage.sh > /dev/null 2>&1
Confirm run script
#!/bin/bash while true do read -p "Are you want to reset the system?(y/n): " _ANSWER if [ x$_ANSWER == 'xn' ];then echo "EXIT" exit fi if [ x$_ANSWER == 'xy' ];then echo "Start" break fi done echo "DONE"
Count Run Time
start_time=`date +%s` # program to run end_time=`date +%s` echo $(($end_time-$start_time))
Get SSL Cert.
getssl.sh
#!/bin/bash _DOMAIN="datahunter.org" _HOST="nginx" mkdir -p /root/scripts/getssl chmod 700 /root/scripts/getssl cd /root/scripts/getssl scp -pr nginx:/etc/letsencrypt/live/$_DOMAIN ./ > /dev/null 2>&1 chmod 400 $_DOMAIN/privkey.pem mv -f $_DOMAIN/privkey.pem /opt/nginx/conf/ssl/ mv -f $_DOMAIN/cert.pem /opt/nginx/conf/ssl/cert.pem cat $_DOMAIN/chain.pem >> /opt/nginx/conf/ssl/cert.pem rm -rf $_DOMAIN nginx -s reload echo "Done"
check disk usage
#!/usr/bin/bash # check /var/www usage _hostname=`hostname` _admin='[email protected]' _data_root=`df -h | awk '$6=="/var/www"{ print $5 }' | tr -d '%'` if [ $_data_root -gt 90 ] then echo "data usage over 90%" echo $_hostname | mail -s "Data Over Usage: $_data_root %" $_admin fi
check file and do something
chkupdate.sh
#!/bin/bash function chkupdate() { cmp $1 $2 > /dev/null 2>&1 if [ $? -eq 0 ] ; then echo "no update" exit else echo "need update" fi } chkupdate old.txt new.txt
syncTime.sh
#!/bin/bash RANGE=600 FLOOR=10 number=0 while [ "$number" -le $FLOOR ] do number=$RANDOM let "number %= $RANGE" done echo "sleep: $number" sleep $number /usr/sbin/ntpdate stdtime.gov.hk /sbin/hwclock -w echo "Done"
crontab
# sync time 0 * * * * /root/script/syncTime.sh > /dev/null 2>&1
bakrotate date folder
bakrotate.sh
#!/bin/bash # create by tim@20170410 #### setting _KEEPCOPY=7 _BACKUPPATH=/backup bakrotate () { local _TMPFILE1=`mktemp` # folder list local _TMPFILE2=`mktemp` # folder need to delete cd $_BACKUPPATH ls -1 -d bak_* | sort -r > $_TMPFILE1 awk "NR > $_KEEPCOPY {print $1}" $_TMPFILE1 > $_TMPFILE2 mkdir _X 2> /dev/null while read line do if [[ $line == 'bak_'* ]]; then mv $line _X else echo "Can not delete $line" fi done < $_TMPFILE2 #### cleanup rm -f $_TMPFILE1 rm -f $_TMPFILE2 } bakrotate
Loop Program
Scripts
#!/bin/bash while : do echo "Press [CTRL+C] to stop.." sleep 1 done
Please note that : is the null command. The null command does nothing and its exit status is always set to true.
( 亦即是相當於 "while true" )
check_httpd.sh
#!/bin/bash file='/usr/share/nginx/html/check_httpd.txt' echo 'Update every min.' > $file echo `date` >> $file echo '===================' >> $file free -m >> $file echo '===================' >> $file netstat -ntp | grep httpd >> $file if [ $? -eq 1 ]; then echo "no connection" >> $file fi
水平線
hr.sh
#!/bin/bash function hr(){ printf '=%.0s' {1..50}; printf "\n" } hr
Result:
# 30 個 "=" ==============================
說明
{}
echo {1..30}
1 2 3 ... 30
Format strings - %s
Interprets the associated argument literally as string
printf '=%s' {1..10}
=1=2=3=4=5=6=7=8=9=10
"." - The dot
Together with a field width, the field is not expanded when the text is longer, the text is truncated instead.
"%.s" is an undocumented equivalent for "%.0s", which will force a field width of zero, effectively hiding the field from output
updatelamp.sh
crontab -e
# Daily Upgrade OS 1 1 * * * /root/scripts/updatelamp.sh > /dev/null 2>&1
chmod 700 /root/scripts/updatelamp.sh
# Web Service yum update -y httpd php roundcubemail phpmyadmin systemctl restart httpd
test for empty directory
pid watchdog
/root/script/assp_watchdog.sh
#!/bin/bash PID=`cat /usr/src/assp/pid` regexp='[^0-9]' if [[ $PID =~ $regexp ]]; then echo "No pid" exit fi ps -p $PID &> /dev/null if [[ $? -eq 1 ]]; then echo "`/bin/date` restart service" /etc/init.d/assp start sleep 10 else echo "assp is working" fi
Count number of file in each sub-folder
count_file.sh
for dir in $(find . -type d); do echo "${dir}: $(find ${dir} -maxdepth 1 -type f | wc -l)" done
Check Partitioning is blank
root-disk-selection.sh
#!/bin/bash # Unit: GB MIN_SIZE=9 MAX_SIZE=11 ROOTDRIVE="" for DEV in sda vda; do bdev=/sys/block/$DEV if [ -d "${bdev}" ] && [ "$(cat ${bdev}/removable)" == "0" ]; then # /sys/block/*/size is in 512 byte chunks devsize=$(($(cat ${bdev}/size)/2**21)) echo "check size for ${DEV}: $devsize GB" if [ "${devsize}" -gt ${MIN_SIZE} ] && [ "${devsize}" -lt ${MAX_SIZE} ]; then if [ -z "$(blkid ${bdev})" ]; then ROOTDRIVE=${DEV} echo $ROOTDRIVE && break fi fi fi done if [ -z "${ROOTDRIVE}" ]; then echo "No ROOTDRIVE" && exit 1 fi
mysql script template
#!/bin/bash mysqluser= mysqlpass= db=mail table=control_relay_ip DDNS=datahunter.org #### Code #### export MYSQL_PWD=$mysqlpass IP=$(dig -t A +short $DDNS) echo $IP sql="UPDATE $db.$table SET ip_address =\"$IP\" WHERE domain=\"$DDNS\" LIMIT 1" mysql -u$mysqluser $db -e "$sql" # OR # echo $sql | -u$mysqluser $db
daily backup report (rsnapshot)
daily-backup-report.sh
#!/bin/bash log=/var/log/rsnapshot mydate=`date +%Y-%m-%d` mydate=`date +%d/%b/%Y` myreport=/tmp/backup_report.txt admin=x@y mysubject="backup_log-`hostname`" tail -n 100 $log | tac | grep $mydate > $myreport echo $mydate | mail -s"$mysubject" -a $myreport $admin
Progress Bar
# Options
- -n : do not append a newline
- -e : enable interpretation of backslash escapes
- \r : carriage return (go back to the beginning of the line without printing a newline)
echo -ne '>> [20%]\r' # some task sleep 2 echo -ne '>>>> [40%]\r' # some task sleep 2 echo -ne '>>>>>> [60%]\r' # some task sleep 2 echo -ne '>>>>>>>> [80%]\r' # some task sleep 2 echo -ne '>>>>>>>>>>[100%]\r' echo -ne '\n'
rsync folder
replicate.sh
#!/bin/bash RSYNC=/usr/bin/rsync DEST=x.x.x.x USER=rsync MODULE=rsync PASS=MYPW EXCLUDEPATTER='--delete-excluded --exclude=_X/ --exclude=_bak/' ############################################################## export RSYNC_PASSWORD=$PASS function syncfolder(){ if [ -d $1 ];then echo `date` > $1/last_sync_time.txt $RSYNC -azvHS \ --bwlimit=3000 \ --delete \ $EXCLUDEPATTER \ $1 \ $USER@$DEST::$MODULE fi } ############################################################## syncfolder /home/vhosts/api/public_html syncfolder /etc/httpd
/etc/rsyncd.conf
# /etc/rsyncd: configuration file for rsync daemon mode uid = root gid = root list = no use chroot = yes max connections = 4 pid file = /var/run/rsyncd.pid exclude = lost+found/ transfer logging = yes log file = /var/log/rsyncd.log timeout = 900 ignore nonreadable = yes dont compress = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2 reverse lookup = no [rsync] path = /home/rsync auth users = rsync secrets file = /etc/rsyncd.secrets read only = no