[Script kid ecstasy] Daily practical script recommendation

Opening narrative:

The script is well written, get off work early! In addition to writing program code in our daily work, we also inevitably need to deal with related testing and verification work.

For example, if access to a certain website has been unavailable, you need to determine whether the address is accessible, what the server returns, and then determine what the problem is. To complete this task, if you blindly hope to use a compiled language to write such code, the time and energy in practice are not enough. At this time, you need to play the magical role of the script!

It's not an exaggeration to say that whether you can write efficient and practical script codes directly affects a programmer's sexual life [off work time]. Here are 13 useful scripts, and use them directly when needed. Collect them!

1. list_sys_status.sh


Display the following information used by the system:
host name, IP address, subnet mask, gateway, DNS server IP address information

#!/bin/bashIP=`ifconfig eth0 | head -2 | tail -1 | awk '{print $2}' | awk -F":" '{print $2}'`ZW=` ifconfig eth0 | head -2 | tail -1 | awk '{print $3}' | awk -F":" '{print $2}'`GW=`route -n | tail -1 | awk '{print $2}'`HN=`hostname`DNS=`head -1 /etc/resolv.conf | awk '{print $2}'`echo '此机IP地址是' $IPecho '此机子网掩码是' $ZWecho '此机网关是' $GWecho '此机主机名是' $HNecho '此机DNS是' $DNS

2. mysqlbak.sh backup database directory script

#!/bin/bashDAY=`date +%Y%m%d`SIZE=`du -sh /var/lib/mysql`echo "Date: $DAY" >> /tmp/dbinfo.txtecho "Data Size: $SIZE" >> /tmp/dbinfo.txtcd /opt/dbbak &> /dev/null || mkdir /opt/dbbaktar zcf /opt/dbbak/mysqlbak-${DAY}.tar.gz /var/lib/mysql /tmp/dbinfo.txt &> /dev/nullrm -f /tmp/dbinfo.txt crontab-e55 23 */3 * * /opt/dbbak/dbbak.sh

3. Make a full backup of the webdb library on the database server at 23:30 every Sunday at midnight


Save each backup file in the /mysqlbak directory of the
system . Use the system date as the backup file name webdb-YYYY-mm-dd.sql
. A new binlog log is generated after each full backup. Back up all
current binlog logs to the /mysqlbinlog directory.

#mkdir /mysqlbak #mkdir /mysqlbinlog#service mysqld startcd /shell#vi webdb.sh#!/bin/bashday=`date +%F`mysqldump -hlocalhost -uroot -p123 webdb > /mysqlbak/webdb-${day}.sqlmysql -hlocalhost -uroot -p -e "flush logs"tar zcf /mysqlbinlog.tar.gz /var/lib/mysql/mysqld-bin.0*#chmod +x webdb.sh #crontab -e30 23 * * 7 /shell/webdb.sh

4. Very.ser.sh (check the running status of any service)


Only check the status of any one of the services vsftpd httpd sshd crond and mysql.
If it is not one of these five services, prompt the user to check the service name and exit the script.
If the service is running, output "service name is running"
if Start the service when it is not running

方法1:使用read写脚本#!/bin/bashread -p "请输入你的服务名:" serviceif [ $service != 'crond' -a $service != 'httpd' -a $service != 'sshd' -a $service != 'mysqld' -a $service != 'vsftpd' ];thenecho "只能够检查'vsftpd,httpd,crond,mysqld,sshd"exit 5fiservice $service status &> /dev/null if [ $? -eq 0 ];thhenecho "服务在线"elseservice $service startfi 或 方法2:使用位置变量来写脚本if [ -z $1 ];thenecho "You mast specify a servername!"echo "Usage: `basename$0` servername"exit 2fiif [ $1 == "crond" ] || [ $1 == "mysql" ] || [ $1 == "sshd" ] || [ $1 == "httpd" ] || [ $1 == "vsftpd" ];thenservice $1 status &> /dev/nullif [ $? -eq 0 ];thenecho "$1 is running"elseservice $1 startfielseecho "Usage:`basename $0` server name"echo "But only check for vsftpd httpd sshd crond mysqld" && exit2fi

5. pc_noline.sh


Output the ip addresses of online hosts in the 192.168.1.0/24 network segment.
Count the number of offline hosts,
and save the ip addresses of offline hosts and the time when they are offline to the file /tmp/ip.txt

#!/bin/baship=192.168.1.j=0for i in `seq 10 12`doping -c 3 $ip$i &> /dev/nullif [ $? -eq 0 ];thenecho 在线的主机有:$ip$ielselet j++echo $ip$i >> /tmp/ip.txtdate >> /tmp/ip.txtfidoneecho 不在线的主机台数有 $j

6. A simple website forum test script


Use interactive input methods to automatically log in to the forum database and modify user passwords

[[email protected] scripts]# vim input.sh #!/bin/bash End=ucenter_membersMYsql=/home/lnmp/mysql/bin/mysql read -p "Enter a website directory : " webdirWebPath=/home/WebSer/$webdir/configecho $WebPath read -p "Enter dbuser name : " dbuserecho $dbuser read -sp "Enter dbuser password : " dbpass read -p "Enter db name : " dbnameecho $dbname read -p "Enter db tablepre : " dbtablepreecho $dbtablepre Globalphp=`grep "tablepre*" $WebPath/config_global.php |cut -d "'" -f8`Ucenterphp=`grep "UC_DBTABLEPRE*" $WebPath/config_ucenter.php |cut -d '.' -f2 | awk -F "'" '{print $1}'` if [ $dbtablepre == $Globalphp ] && [ $dbtablepre == $Ucenterphp ];then      Start=$dbtablepre     Pre=`echo $Start$End`      read -p "Enter you name : " userset     echo $userset      Result=`$MYsql -u$dbuser -p$dbpass $dbname -e "select username from $Pre where username='$userset'\G"|cut -d ' ' -f2|tail -1`     echo $Result     if [ $userset == $Result ];then           read -p "Enter your password : " userpass           passnew=`echo -n $userpass|openssl md5|cut -d ' ' -f2`            $MYsql -u$dbuser -p$dbpass $dbname -e "update $Pre set password='$passnew' where username='$userset';"           $MYsql -u$dbuser -p$dbpass $dbname -e "flush privileges;"     else           echo "$userset is not right user!"           exit 1     fielse     exit 2fi

7, slave_status.sh (check the status of the slave database server in the mysql master-slave structure)


1) Whether the database service of this machine is running
2) Whether it can communicate with the main database server normally
3) Whether it can connect to the database server with an authorized user
4) Whether the slave_IO process of
this machine is in YES state Whether the slave_SQL process of this machine is in YES state

[[email protected] scripts]# vim test.sh #!/bin/bashnetstat -tulnp | grep :3306 > /dev/nullif [ $? -eq 0 ];thenecho "服务正在运行" elseservice mysqld startfiping -c 3 192.168.1.100 &> /dev/nullif [ $? -eq 0 ];thenecho "网络连接正常" elseecho "网络连接失败"fimysql -h192.168.1.100 -uroot -p123456 &> /dev/nullif [ $? -eq 0 ];thenecho "数据库连接成功" elseecho "数据库连接失败"fiIO= mysql -uroot -p123 -e "show slave status\G" | grep Slave_IO_Running | awk '{print $2}' > /dev/nullSQL= mysql -uroot -p123 -e "show slave status\G" | grep Slave_SQL_Running | awk '{print $2}' /dev/nullif [ IO==Yes ] && [ SQL==Yes ];thenecho “IO and SQL 连接成功”elseecho "IO线程和SQL线程连接失败"fi

8. Refuse ssh connection for ip that has logged in more than n times

结合/var/log/secure文件,将ssh登陆失败次数大于N的IP封顶 N=3SEC_FILE=/var/log/securefor ip in `grep "Failed password" $SEC_FILE|grep -Eo "([0-9]{1,3}\.){3}[0-9]{1,3}"|sort -n|uniq -c|awk '{if($1>$N) print $2}'`doiptables -A INPUT -s $ip -p tcp --dport 22 -j DROPdone

9. CentOS7 prevents malicious cracking of root account scripts

#!/bin/bash#Denyhosts SHELL SCRIPT#2017-01-24##When a IP is accessed 50 times through sshd, it is written to the hosts.deny file, #which prohibits the IP from connecting to the host via sshd##Add to timing task cat /var/log/secure | awk '/Failed/{print $(NF-3)}' | sort | uniq -c | awk '{print $2"="$1;}' > /root/black.txt DEFINE=50for i in $(cat /root/black.txt)do    IP=$( $i | awk -F'=' '{print $1}')    NUM=$( $i | awk -F'=' '{print $2}')    if [$NUM -gt $DEFINE]; then        grep $IP /etc/hosts.deny > /dev/null        if [$? -gt 0];then            echo "sshd:$IP" >> /etc/hosts.deny        fi    fidone

10. View the real-time traffic of the network card

# vi check_network.sh "#!/bin/bashNIC=$1echo -e "" In ------ Out""while true; doOLD_IN=$(awk '$0~""'$NIC'""{print $2}' /proc/net/dev)OLD_OUT=$(awk '$0~""'$NIC'""{print $10}' /proc/net/dev)sleep 1NEW_IN=$(awk '$0~""'$NIC'""{print $2}' /proc/net/dev)NEW_OUT=$(awk '$0~""'$NIC'""{print $10}' /proc/net/dev)IN=$(printf ""%.1f%s"" ""$((($NEW_IN-$OLD_IN)/1024))"" ""KB/s"")OUT=$(printf ""%.1f%s"" ""$((($NEW_OUT-$OLD_OUT)/1024))"" ""KB/s"")echo ""$IN $OUT""sleep 1done" 执行:sh check.sh ens33

11. Check whether the website can be accessed in batches

# vi check_web.sh "#!/bin/bashURL_LIST=""www.baidu.com www.sina.cn""for URL in $URL_LIST; doFAIL_COUNT=0for ((i=1;i<=3;i++)); doHTTP_CODE=$(curl -I -m 10 -o /dev/null -s -w %{http_code} $URL)if [ $HTTP_CODE -eq 200 ]; thenecho ""$URL OK""breakelseecho ""$URL retry $FAIL_COUNT""let FAIL_COUNT++fidoneif [ $FAIL_COUNT -eq 3 ]; thenecho ""Warning: $URL Access failure!""fidone"

12. Check the MySQL master-slave synchronization status

# vi check_mysql.sh "#!/bin/bashUSER=bakPASSWD=123456IO_SQL_STATUS=$(mysql -u$USER -p$PASSWD -e 'show slave statusG' |awk -F:'/Slave_.*_Running/{gsub("": "","":"");print $0}') #gsub 去除冒号后面的空格for i in $IO_SQL_STATUS; doTHREAD_STATUS_NAME=${i%:*}THREAD_STATUS=${i#*:}if [ ""$THREAD_STATUS"" != ""Yes"" ]; thenecho ""Error: MySQL Master-Slave $THREAD_STATUS_NAME status is $THREAD_STATUS!""fidone"

13, DDOS attack nginx prevention

"#!/bin/bashDATE=$(date +%d/%b/%Y:%H:%M)LOG_FILE=/etc/nginx/logs/access.logABNORMAL_IP=$(tail -n5000 $LOG_FILE |grep $DATE |awk '{a[$1]++}END{for(i in a)if(a[i]>10)print i}')for IP in $ABNORMALIP; doif [ $(iptables -vnL |grep -c ""$IP"") -eq 0 ]; theniptables -I INPUT -s $IP -j DROPecho ""$(date +'%F%T') $IP"" >> /tmp/drop_ip.logfidone"

I also wrote a lot of daily practical scripts because of too much space. Friends in need can scan the QR code below after three friendships: csdn to receive them!