Shell脚本习题集-每日一练

本文提供了一系列针对Linux系统的优化及管理脚本,包括数据库备份、简易跳板机搭建、一键系统优化、服务监控与管理等实用脚本。这些脚本能够帮助系统管理员高效完成日常任务。

2017/9/4

msyql数据库分库备份

 1 #!/usr/bin/env bash
 2 #
 3 
 4 #Author       :  JACK ZHAO
 5 #Date         :  2017/09/25
 6 #Descriptions :  Database repository backup
 7 
 8 USERNAME=root
 9 PASSWD=oldboy123
10 MYDUMP=/application/mysql/bin/mysqldump
11 SOCK=/data/3306/mysql.sock
12 export PATH=/application/mysql/bin:$PATH
13 
14 . /etc/init.d/functions
15 
16 [ -e /data/backup ] || mkdir -p /data/backup
17 DB=`/application/mysql/bin/mysql -u$USERNAME -p$PASSWD -S $SOCK -e "show databases;" | grep -iEv "mysql|Database|infor|perfor"`
18 for i in `echo $DB`;do
19   $MYDUMP -u$USERNAME -p$PASSWD -S $SOCK --default-character-set=latin1 --events -B $i | gzip -9 > /data/backup/${i}_`date +%F`.gz
20   if [ $? -eq 0  ];then
21     action "$i succeed. /data/backup/${i}_`date +%F`.gz"   /bin/true
22   else
23     action "$i failed."  /bin/false
24   fi
25 done
26 坑点:如果加载了. /etc/init.d/functions,在脚本中不能用直接用mysql,而要使用全路径,原因不详,可能因为functions中使用mysql
View Code

 

2017/9/3

简易跳板机

 1 1)首先做好SSH密钥验证(跳板机地址192.168.33.128)。
 2 以下操作命令在所有机器上操作:
 3 [root@mylab3 ~]# useradd jumper #<==要在所有机器上操作。
 4 以下操作命令仅在跳板机上操作:
 5 [root@mylab3 ~]# su - jumper
 6 [jump@mylab3 ~]$ ssh-keygen -t dsa -P '' -f ~/.ssh/id_dsa >/dev/null 2>&1  #<==生成密钥对。
 7 2)将公钥分发到其他服务器。192.168.0.108 192.168.0.110 192.168.0.200
 8 [jump@mylab3 ~]$ ssh-copy-id -i ~/.ssh/id_dsa.pub 192.168.0.108   #<==将公钥分发到其他服务器。
 9 The authenticity of host '192.168.0.108 (192.168.0.108)' can't be established.
10 RSA key fingerprint is fd:2c:0b:81:b0:95:c3:33:c1:45:6a:1c:16:2f:b3:9a.
11 Are you sure you want to continue connecting (yes/no)? yes
12 Warning: Permanently added '192.168.0.108' (RSA) to the list of known hosts.
13 jumper@192.168.0.108's password:
14 Now try logging into the machine, with "ssh '192.168.0.108'", and check in:
15  
16   .ssh/authorized_keys
17  
18 to make sure we haven't added extra keys that you weren't expecting.
19 
20 #!/usr/bin/env bash
21 #
22 
23 # Author       : Jack zhao
24 # Date         : 2017/9/22
25 # Descriptsion : Simple jumpe Server.
26 
27 while true;do
28 trap ':' INT TSTP TERM EXIT
29 clear 
30 cat << EOF
31 ========Jumper Server========
32 [1] ## 192.168.0.108
33 [2] ## 192.168.0.110
34 [3] ## 192.168.0.200
35 EOF
36   read -p "Please Choose the number [1-3]:" NUM
37   case $NUM in 
38   1)
39     echo "Login 192.168.0.108"
40     ssh 192.168.0.108
41     ;;
42   2)
43     echo "Login 192.168.0.110"
44     ssh 192.168.0.110
45     ;;
46   3)
47     echo "Login 192.168.0.200"
48     ssh 192.168.0.200
49     ;;
50   110)
51     read -p "Enter The code of our department for jumper shell:" DEPT
52     if [ "$DEPT" == "646427" ];then
53       exit 0
54       sleep 3
55     else
56       echo "The code is wrong."
57       sleep 2
58     fi
59     ;;
60   *)
61     echo "Please enter a valid number."
62     sleep 2
63     ;;
64   esac
65 done
66 
67 #添加至/etc/profile.d,登陆或切换至jumper用户时执行
68 [root@oldboy ~]# echo '[ $UID -ne 0 ] && . /server/scripts/jump.sh' >/etc/profile.d/jump.sh
View Code

 

2017/9/2

 Linux一键优化

1.安装系统时精简安装(最小化安装)

2.配置国内高速yum源

3.禁用开机不需要启动的服务

4.优化系统内核参数/etc/sysctl.conf

5.增加系统文件描述符,堆栈等配置

6.禁止root远程登录,修改SSH端口为特殊端口,禁止DNS,空密码

7.有外网IP的机器需要开启配置防火墙,仅对外开启需要提供服务的端口,配置或关闭selinux

8.清除无用的默认系统账户或组(非必须)

9.锁定敏感文件,如/etc/passwd

10.配置服务器和互联网时间同步

11.配置sudo对普通用户权限精细控制

  1 #!/usr/bin/env bash
  2 #
  3 
  4 # Author      : JACK ZHAO
  5 # Date        : 2017/09/15
  6 # Description : Linux simple optimization.
  7 
  8 #####global variables#####
  9 export PATH=$PATH
 10 RC=0
 11 OPTIMIZELOG=/tmp/optimize.log.`date '+%F-%T'`
 12 
 13 #####Precheck#####
 14 [ `id -u` -ne 0  ] && echo "Warning:You must run this script as root." &&  exit 1
 15 [ `awk -F "." '{print$1}'  /etc/redhat-release | egrep "CentOS release 5|CentOS release 6|CentOS release 7" -c` -ne 1 ] && \
 16 echo "Warining:This script is only suitable for the Centos5/6/7." 
 17 
 18 #####stty erase ^H#####
 19 /bin/stty erase ^H
 20 
 21 #####set LANG#####
 22 export LANG=zh_CN.UTF-8
 23 
 24 #####load functions#####
 25 . /etc/init.d/functions
 26 
 27 #####Common functions#####
 28 succeed(){
 29   action "$1" /bin/true
 30   return  0
 31 }
 32 
 33 failed(){
 34  action "$1" /bin/false
 35  return 0
 36 }
 37 
 38 #####163 yum configuration source#####
 39 initYum(){
 40   echo "----->Starting Yum configuration source" | tee -a $OPTIMIZELOG
 41   /usr/bin/wget --spider -q  http://mirrors.163.com/
 42   RC=$?
 43   if [ $RC -eq 0 ];then
 44     [ -e /etc/yum.repos.d/CentOS-Base.repo ]  && \
 45     mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bak.`date +'%F-%T'` -v &>> $OPTIMIZELOG
 46     local VERSION=`awk -F "[ .]+" '{print$3}' /etc/redhat-release`
 47     if [ $VERSION -eq 5 ];then
 48       wget -q -P /etc/yum.repos.d/ http://mirrors.163.com/.help/CentOS5-Base-163.repo
 49     elif [ $VERSION -eq 6 ];then 
 50       wget -q -P /etc/yum.repos.d/ http://mirrors.163.com/.help/CentOS6-Base-163.repo
 51     elif [ $VERSION -eq 7 ];then
 52       wget -q -P /etc/yum.repos.d/ http://mirrors.163.com/.help/CentOS7-Base-163.repo
 53     fi 
 54     /bin/mv  /etc/yum.repos.d/*-Base-163.repo /etc/yum.repos.d/CentOS-Base.repo -v &>> $OPTIMIZELOG
 55     yum clean all &>> $OPTIMIZELOG  && yum makecache &>> $OPTIMIZELOG
 56     echo "#####yum repolist#####" | tee -a $OPTIMIZELOG
 57     yum repolist | tee -a $OPTIMIZELOG
 58   fi
 59   if [ $RC -eq 0 ];then
 60     succeed "Yum configuration source." | tee -a $OPTIMIZELOG
 61   else 
 62     failed "Yum configuration source."  | tee -a $OPTIMIZELOG
 63   fi
 64   return $RC
 65 }
 66 
 67 #####Streamline startup daemon services#####
 68 initService(){
 69   echo "----->Starting streamline daemon services" | tee -a $OPTIMIZELOG
 70   local VERSION=`awk -F "[ .]+" '{print$3}' /etc/redhat-release`
 71   if [ $VERSION -eq 5 ] || [ $VERSION -eq 6 ];then
 72     echo "#####service crond stop#####" | tee -a $OPTIMIZELOG
 73     for i in acpid cpuspeed cups ip6tables ;do
 74       /etc/init.d/$i stop | tee -a $OPTIMIZELOG
 75     done 
 76     echo "#####chkconfig off #####" | tee -a $OPTIMIZELOG
 77     for i in acpid cpuspeed cups ip6tables bluetooth;do
 78       chkconfig $i off
 79       echo "chkconfig $i off" | tee -a $OPTIMIZELOG
 80     done 
 81     echo "#####chkconfig --list#####" | tee -a $OPTIMIZELOG
 82     export LANG=en_USA.UTF-8
 83     chkconfig --list |grep 3:on | tee -a $OPTIMIZELOG 
 84     export LANG=zh_CN.UTF-8
 85     succeed "Starting stramline daemo services." | tee -a $OPTIMIZELOG
 86     return 0
 87   else
 88     failed "Starting stramline daemo services." | tee -a $OPTIMIZELOG
 89     return 110
 90   fi
 91 }
 92 
 93 #####Optimize the system kernel parameters#####
 94 initKernel(){
 95   echo "----->Starting optimize system kernel parameters" | tee -a $OPTIMIZELOG
 96   [ -w /etc/sysctl.conf ] &&  mv /etc/sysctl.conf /etc/sysctl.conf.`date +'%F-%T'`
 97   cat >>/etc/sysctl.conf<<EOF
 98 net.ipv4.tcp_fin_timeout = 2
 99 net.ipv4.tcp_tw_reuse = 1
100 net.ipv4.tcp_tw_recycle = 1
101 net.ipv4.tcp_syncookies = 1
102 net.ipv4.tcp_keepalive_time = 600
103 net.ipv4.ip_local_port_range = 4000 65000
104 net.ipv4.tcp_max_syn_backlog = 16384
105 net.ipv4.tcp_max_tw_buckets = 36000
106 net.ipv4.route.gc_timeout = 100
107 net.ipv4.tcp_syn_retries = 1
108 net.ipv4.tcp_synack_retries = 1
109 net.core.somaxconn = 16384
110 net.core.netdev_max_backlog = 16384
111 net.ipv4.tcp_max_orphans = 16384
112 net.netfilter.nf_conntrack_max = 25000000
113 net.netfilter.nf_conntrack_tcp_timeout_established = 180
114 net.netfilter.nf_conntrack_tcp_timeout_time_wait = 120
115 net.netfilter.nf_conntrack_tcp_timeout_close_wait = 60
116 net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 120
117 kernel.sysrq = 0
118 kernel.core_uses_pid = 1
119 kernel.msgmnb = 65536
120 kernel.msgmax = 65536
121 kernel.shmmax = 68719476736
122 kernel.shmall = 4294967296
123 EOF
124   cp /etc/rc.local /etc/rc.local.`date '+%F-%T'`  
125   modprobe nf_conntrack
126   echo "modprobe nf_conntrack" >> /etc/rc.local 
127   modprobe bridge 
128   echo "modprobe bridge">> /etc/rc.local
129   echo "#####Kernel Parameters#####"
130   /sbin/sysctl -p | tee -a $OPTIMIZELOG
131   RC_VALUE=$?
132   if [ $RC_VALUE -eq 0 ];then
133     succeed "Optimize the system kernel parameters" | tee -a $OPTIMIZELOG
134   else
135     failed "Optimize the system kernel parameters" | tee -a $OPTIMIZELOG
136   fi
137   return $RC_VALUE
138 }
139 
140 #####Add system file descriptors, stacks, and other configurations#####
141 initLimits(){
142   echo "----->Starting Add system file descriptors" | tee -a $OPTIMIZELOG
143   local VALUES=`grep -v "^#" /etc/security/limits.conf | grep -E "nproc|nofile" | wc -l`
144   if [ -w /etc/security/limits.conf ] && [ $VALUES -eq 0 ];then
145     cp /etc/security/limits.conf /etc/security/limits.conf.`date +'%F-%T'` -v  >>  $OPTIMIZELOG
146     cat >> /etc/security/limits.conf << EOF
147 * soft nproc 2047
148 * hard nproc 16384
149 * soft nofile 2048
150 * hard nofile 65536
151 EOF
152     source /etc/security/limits.conf  2>/dev/null
153     echo "#####File Descriptors#####"
154     grep  -E -v "^#|^$" /etc/security/limits.conf  | tee -a $OPTIMIZELOG
155     succeed "Add system file descriptiors" | tee -a $OPTIMIZELOG
156     return 0
157   else
158     failed "Add system file descriptiors" | tee -a $OPTIMIZELOG
159     return 110
160   fi
161 }
162 
163 #####Close selinux and iptables#####
164 initFirewall(){
165   echo "----->Starting Close selinux and clear iptables"
166   /sbin/iptables -F >>  $OPTIMIZELOG
167   /etc/init.d/iptables save >> $OPTIMIZELOG
168   local VALUES=`grep -w -c "^SELINUX=diabled" /etc/selinux/config`
169   if [ $VALUES -eq 0 ] && [ -w /etc/selinux/config ];then
170     cp /etc/selinux/config /etc/selinux/config.`date '+%F-%T'` -v >> $OPTIMIZELOG
171     sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config   
172     setenforce 0 
173     echo "#####Selinux status#####" | tee -a $OPTIMIZELOG
174     echo "Selinux:`getenforce`" | tee -a $OPTIMIZELOG
175     echo "#####Iptables status#####" | tee -a $OPTIMIZELOG
176     /etc/init.d/iptables status | tee -a $OPTIMIZELOG
177     succeed "Close selinux and iptables" | tee -a $OPTIMIZELOG
178     return 0
179   else
180     failed "Close selinux and iptables" | tee -a $OPTIMIZELOG
181     return 110
182   fi
183 }
184 
185 #####Clear unused accounts and groups#####
186 initUser(){
187   echo "----->Starting Clear unused accounts,groups and add user"
188   echo "#####Delete User#####" | tee -a $OPTIMIZELOG
189   for i in lp shutdown halt uucp operator games gopher;do
190     /usr/sbin/userdel  -r $i 2>/dev/null || continue
191     echo "Deleted user $i" | tee -a $OPTIMIZELOG
192   done
193   echo "#####Delete Group#####" | tee -a $OPTIMIZELOG
194   for i in lp uucp operator games gopher;do
195     /usr/sbin/groupdel $i 2>/dev/null || continue
196     echo "Deleted group $i" | tee -a $OPTIMIZELOG
197   done
198   echo "#####Add user#####" | tee -a $OPTIMIZELOG
199   grep -q '^user01' /etc/passwd && userdel -r user01   
200   useradd  user01
201   id user01 | tee -a $OPTIMIZELOG
202   if [ -w /etc/shadow ];then
203     sed -i 's/user01:!!/user01:$1$8tqGkiME$fThWs5EfPyzlxI8F6mq6E1/g' /etc/shadow
204     succeed "Clear unused accounts,groups and add user." | tee -a $OPTIMIZELOG
205     return 0
206   else
207     failed "Add user user01" | tee -a $OPTIMIZELOG
208     return 110
209   fi
210 }
211 
212 #####Synchronization time#####
213 initSyncTime(){
214   echo "----->Starting Synchronization time"
215   local ZONEINFO=`/bin/date  -R | awk '{print$NF}'`
216   if [ "$ZONEINFO" != "+0800" ];then
217     /bin/mv  /etc/localtime  /etc/localtime.`date +'%F-%T'`.bak
218     cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime -v >>  $OPTIMIZELOG
219   fi
220   echo "#####Synch Time Aliyum#####" | tee -a $OPTIMIZELOG
221   if [ -e /var/spool/cron/root ];then
222     local NTPDATE=`grep -c "ntpdate" /var/spool/cron/root 2>/dev/null`
223     if [ $NTPDATE -eq 0 ];then
224       cp /var/spool/cron/root  /var/spool/cron/root.`date '+%F-%T'` -v >> $OPTIMIZELOG
225       echo "*/5 * * * * /usr/sbin/ntpdate -u time1.aliyun.com  &>/dev/null" >> /var/spool/cron/root
226     fi
227   else
228     touch /var/spool/cron/root
229     echo "*/5 * * * * /usr/sbin/ntpdate -u time1.aliyun.com  &>/dev/null" >> /var/spool/cron/root
230   fi
231    echo "#####Crontab#####" | tee -a $OPTIMIZELOG
232   /usr/bin/crontab -l | tee -a $OPTIMIZELOG 
233   /usr/sbin/ntpdate -u  time1.aliyun.com | tee -a $OPTIMIZELOG
234   if [ $? -eq 0 ];then
235     succeed "Synchronization time" | tee -a $OPTIMIZELOG
236     return 0
237   else
238     failed  "Synchronization time" | tee -a $OPTIMIZELOG
239     return 110
240   fi
241 }
242 
243 #####Configure the sudo permissions for normal users#####
244 initSudo(){
245   echo "----->Starting Configure sudo permissions for normal users"
246   local VALUES=`grep -c "user01" /etc/sudoers`
247   if [ $VALUES -eq 0 ];then
248     echo "#####Sudo Permissions#####"
249     echo "user01  ALL=(ALL)       NOPASSWD: ALL" >>/etc/sudoers
250     grep '^user01' /etc/sudoers | tee -a $OPTIMIZELOG
251     succeed "Confiure the sudo permissions for normal user" | tee -a $OPTIMIZELOG
252     return 0
253   else
254     failed "Confiure the sudo permissions for normal user" | tee -a $OPTIMIZELOG
255     return 110
256   fi
257 }
258 
259 #####Modify the system character set as zh_cn.utf-8#####
260 initI18n(){
261   echo "----->Modify System Character" | tee -a $OPTIMIZELOG
262   local VALUES=`grep -c "zh_cn.utf-8" /etc/sysconfig/i18n` 
263   if [ $VALUES -eq 0 ];then
264     mv /etc/sysconfig/i18n /etc/sysconfig/i18n.`date +'%F-%T'`.bak    
265     echo "LANG="zh_CN.UTF-8"" >> /etc/sysconfig/i18n | tee -a $OPTIMIZELOG
266     echo "SYSFONT="latarcyrheb-sun16"" >> /etc/sysconfig/i18n | tee -a $OPTIMIZELOG
267     echo "#####LANG#####"
268     source /etc/sysconfig/i18n 
269     echo  $LANG | tee -a $OPTIMIZELOG
270     succeed  "Modify the system character." | tee -a $OPTIMIZELOG
271     return 0
272   else 
273     failed "Modify the system character." | tee -a $OPTIMIZELOG
274     return 110
275   fi
276 }
277 
278 #####Lock sensitive file#####
279 initChattr(){
280   echo "----->Starting Lock sensitive file" | tee -a $OPTIMIZELOG
281   echo "#####Lock /etc/passwd#####" | tee -a $OPTIMIZELOG
282   chattr  +i /etc/passwd 
283   lsattr  /etc/passwd | tee -a $OPTIMIZELOG
284   echo "#####Lock /etc/inittb#####" | tee -a $OPTIMIZELOG
285   chattr +i /etc/inittab
286   lsattr /etc/inittab | tee -a $OPTIMIZELOG
287   echo "#####Lock /etc/group#####" | tee -a $OPTIMIZELOG
288   chattr +i /etc/group
289   lsattr /etc/group | tee -a $OPTIMIZELOG
290   echo "#####Lock /etc/shadow#####" | tee -a $OPTIMIZELOG
291   chattr +i /etc/shadow
292   lsattr /etc/shadow | tee -a $OPTIMIZELOG
293   echo "#####Lock /etc/shadow#####" | tee -a $OPTIMIZELOG
294   chattr +i /etc/gshadow
295   lsattr /etc/gshadow | tee -a $OPTIMIZELOG
296   succeed  "Lock sensitive file" | tee -a $OPTIMIZELOG
297   return 0
298 }
299 
300 #####Modify SSH login port, prohibit root remote login, disable DNS#####
301 initsshd(){
302   echo "----->Starting configure SSH" | tee -a $OPTIMIZELOG
303   cp /etc/ssh/sshd_config  /etc/ssh/sshd_config.`date '+%F-%T'` >>  $OPTIMIZELOG
304   echo "#####Set Port 22 TO 52113#####" | tee -a $OPTIMIZELOG  
305   sed -i 's/#Port 22/Port 52113/g' /etc/ssh/sshd_config
306   grep "^Port"  /etc/ssh/sshd_config | tee -a $OPTIMIZELOG
307   echo "#####NO PermitRootLogin#####" | tee -a $OPTIMIZELOG
308   sed -i 's/#PermitRootLogin yes/PermitRootLogin no/g'  /etc/ssh/sshd_config
309   grep "^PermitRootLogin"  /etc/ssh/sshd_config | tee -a $OPTIMIZELOG
310   echo "#####NO PermitEmptyPasswords" | tee -a $OPTIMIZELOG
311   sed -i 's/#PermitEmptyPasswords/PermitEmptyPasswords/g' /etc/ssh/sshd_config
312   grep "^PermitEmptyPasswords" /etc/ssh/sshd_config | tee -a $OPTIMIZELOG
313   echo "#####NO UseDNS#####" | tee -a $OPTIMIZELOG
314   sed -i 's/#UseDNS yes/UseDNS no/g' /etc/ssh/sshd_config
315   grep "^UseDNS" /etc/ssh/sshd_config | tee -a $OPTIMIZELOG
316   /etc/init.d/sshd restart &>/dev/null
317   if [ $? -eq 0 ];then
318      succeed "Configure SSH Service." | tee -a $OPTIMIZELOG
319      return 0
320   else
321      failed  "Configure SSH Service." | tee -a $OPTIMIZELOG
322      return 110
323   fi
324 }
325 
326 ##### A key optimization#####
327 key(){
328  initYum
329  initService
330  initKernel
331  initLimits
332  initFirewall
333  initUser
334  initSyncTime
335  initSudo
336  initI18n
337  initChattr
338  initsshd
339 }
340 
341 custom(){
342   while true;do
343     cat << EOF
344 ==============Custom Optimization ======================
345 [1]  ## Yum configuration source
346 [2]  ## Streamline system services
347 [3]  ## Optimization of the kernel
348 [4]  ## Configure Limits
349 [5]  ## Configure Firewall
350 [6]  ## Configure User
351 [7]  ## Sync Time
352 [8]  ## Configure Sudo
353 [9]  ## Modify System character
354 [10] ## Add chattr File
355 [11] ## Configure SSH
356 [0]  ## Return to the upper level
357 =========================================================
358 EOF
359     read -p "Please select the number:" CHOICE2
360     case $CHOICE2 in 
361       1)
362        initYum
363        ;;
364       2)
365        initService
366        ;;
367       3)
368        initKernel
369        ;;
370       4)
371        initLimits
372        ;;
373       5)
374        initFirewall
375        ;;
376       6)
377        initUser
378        ;;
379       7)
380        initSyncTime
381        ;;
382       8)
383        initSudo
384        ;;
385       9)
386        initI18n
387        ;;
388       10)
389        initChattr
390        ;;
391       11)
392        initsshd
393        ;;
394       0)
395        clear
396        mainmeun
397        ;;
398       *)
399        echo "Input invalid please re-enter."
400        for i in  `seq 3 -1 1`;do
401          echo -ne "\b\b\b[$i]"
402          sleep 1
403        done
404        clear
405     esac
406   done
407 }
408 
409 #####print main meun#####
410 mainmeun(){
411   while true;do
412   cat << EOF
413 ====================Linux optimization====================
414 Current time : $CURRENT_TIME
415 IP       : $IPINFO
416 Serial Number: $SERIAL_NUMBER
417 CPU Model    : $CPU_MODEL 
418 Memtotal     : $MEMTOTAL
419 DISK         : $DISKINFO
420 LOAD AVERAGE : $UPTIMES
421 OS       : $OSINFO
422 ==========================================================
423 [1] ## A key to optimize
424 [2] ## Custom optimization
425 [0] ## exit
426 EOF
427   read -p "Please select the number:" CHOICE1
428     case $CHOICE1 in
429       1)
430         echo -e "**********It takes a few minutes to optimize**********" | tee -a $OPTIMIZELOG
431         key
432         echo -e "**********A key optimization is completed**********\n\n" | tee -a $OPTIMIZELOG
433         ;;
434       2)
435        clear
436        custom
437        ;;
438       0)
439        exit 0
440        ;;
441       *)
442        echo "Input invalid please re-enter."
443        for i in  `seq 3 -1 1`;do
444          echo -ne "\b\b\b[$i]"
445          sleep 1
446        done
447        clear
448     esac
449   done
450 }
451 
452 #####system information#####
453 CURRENT_TIME=`date '+%F %T'`
454 SERIAL=`dmidecode -t 1 | awk -F: '$1 ~ "Serial Number"{print$2}' | sed -r 's/^[[:space:]]+//g'`
455 SERIAL_NUMBER=${SERIAL:-NULL}
456 CPU=`grep "model name" /proc/cpuinfo | awk -F: '{print$2}' | sed 's/ //g'`
457 CPU_MODEL=${CPU:-NULL}
458 MEM=`grep 'MemTotal' /proc/meminfo  | awk -F: '{print$2}' | sed -r  's/^[[:space:]]+//g'`
459 MEMTOTAL=${MEM:-NULL}
460 DISK=`fdisk  -l | grep "^Disk /dev" | awk -F "[:,]" '{print$2}' | sed -r 's/^[[:space:]]+//g'`
461 DISKINFO=${DISK:-NULL}
462 UPTIME=`uptime | awk -F ":" '{print$NF}' | sed -r 's/^[[:space:]]+//g' `
463 UPTIMES=${UPTIME:-NULL}
464 OS=`cat /etc/redhat-release`
465 OSINFO=${OS:-NULL}
466 IP=`ip addr show eth0 | grep -w 'inet' | awk -F "[ /]+" '{print$3}'`
467 IPINFO=${IP:-NULL}
468 
469 mainmeun
View Code

 

2017/9/1

rsync服务启动脚本

 1 #!/usr/bin/env bash
 2 #
 3 # rsync       Bring start/stop rsyncd
 4 #
 5 # chkconfig: 2345 50 50
 6 # description: Start or close the rsync service.
 7 
 8 export PATH=/usr/bin/:$PATH
 9 LOCKFILE=/var/lock/subsys/rsync
10 RETURN=0
11 
12 . /etc/init.d/functions
13 
14 start(){
15   VALUES=`ss -anlp | grep 873 | wc -l`
16   if [ $VALUES  -eq 2 ];then
17      echo "Rsync is running..."
18   else
19      /usr/bin/rsync --daemon --config=/etc/rsyncd.conf 
20      RETURN=$?
21      if [ $RETURN -eq 0 ];then
22        action "Starting rsync..." /bin/true
23        [ ! -e $LOCKFILE ] &&  touch $LOCKFILE  
24      else
25        action "Starting rsync..." /bin/false
26      fi
27   fi
28   return $RETURN
29 }
30 
31 stop(){
32   VALUES=`ss -anlp | grep 873 | wc -l`
33   if [ $VALUES -eq 0 ];then
34     echo "Rsync is stopped."
35   else
36     killall rsync  &>/dev/null
37     RETURN=$?
38     if [ $? = 0 ];then
39       action "Stopping rsync..." /bin/true
40       [ -e $LOCKFILE ] && rm -f $LOCKFILE
41     else
42       action "Stopping rsync..." /bin/false
43     fi
44   fi
45   return $RETURN 
46 }
47 
48 status(){
49   if [ -e $LOCKFILE ];then
50     echo "Rsync is running..."
51   else
52     echo "Rsync is stopped."
53   fi
54   return $VALUES
55 }
56 
57 case $1 in
58 start)
59   start
60   ;;
61 stop)
62   stop
63   ;;
64 restart|reload|force-reload)
65   $0 stop
66   sleep 3
67   $0 start
68   RETURN=$?
69   ;;
70 status)
71   status
72   ;;
73 *) 
74  echo "Usage: $0 {start|stop|status|reload|force-reload}"
75  exit 2
76 esac
77 exit $RETURN
View Code

 

2017/8/31

mysql启动、关闭

 1 #!/usr/bin/env bash
 2 #
 3 #Author      : JACK ZHAO
 4 #Date        : 2017/9/13
 5 #Description : This script is used for mysql to start and stop.
 6 
 7 export PATH=$PATH:/application/mysql/bin/
 8 lockdir=/var/lock/subsys
 9 lockfile="$lockdir/mysql"
10 basedir=/application/mysql/bin
11 datadir=/data/3306
12 mysqlpidfile="$datadir/`hostname`.pid"
13 mycnf="$datadir/my.cnf"
14 returnvalue=0
15 
16 . /etc/init.d/functions
17 
18 mysqlstart(){
19  [ -e $lockfile ] && echo "MySQL is running..." && exit 0
20  /bin/sh $basedir/mysqld_safe --defaults-file=$mycnf --pid-file=$mysqlpidfile 2>&1 >/dev/null &
21  returnvalue=$?
22  if [ $returnvalue -eq 0 ];then
23    action "Starting MySQL..." /bin/true
24    touch $lockfile
25  else
26    action "Starting MySQL..." /bin/false
27  fi
28  return $retunvalue
29 }
30 
31 mysqlstop(){
32  [ ! -e $mysqlpidfile ] && echo "MySQL is stopped." && return 0
33  mysqlpid=`cat $mysqlpidfile`
34  kill -0 $mysqlpid &>/dev/null
35  returnvalue=$?
36  if [ $returnvalue -eq 0 ];then
37    sleep 2
38    kill $mysqlpid &>/dev/null
39    returnvalue=$?
40    if [ $returnvalue -eq 0 ];then
41      action "Stopping MySQL..." /bin/true
42    else
43      action "Stopping MySQL..." /bin/false
44    fi  
45  else
46    action "Mysqld pid non-exists.Stop MySQL..."
47  fi 
48  [ -e $lockfile ] && rm  -f $lockfile
49  return $returnvalue
50 }
51 
52 mysqlstatus(){
53  if [ -e $lockfile ];then
54   echo "MySQL is running..."
55  else
56   echo "MySQL is stopped."
57  fi
58  return 0
59 }
60 
61 usage(){
62 echo "Usage:sh `basename $0` [start|stop|restart|status]"
63 echo "Description: This script is used for mysql to start, close, and view the state"
64 }
65 
66 case $1 in 
67 start)
68    mysqlstart 
69    ;;
70 stop)
71    mysqlstop
72    ;;
73 restart)
74    mysqlstop
75    sleep 3
76    mysqlstart
77    ;;
78 status)
79    mysqlstatus
80    ;;
81 *)
82   usage
83   exit 1
84 esac
85 exit $returnvalue
View Code

 

2017/8/30

memcache监控状态

1 #!/usr/bin/env bash
2 #
3 
4 MEMCACHE_PRO=`netstat -anlp | grep 11212 | wc -l`
5 if [ $MEMCACHE_PRO -eq 2 ];then
6   echo "Memcache is running..."
7 else
8   echo "Memcache is expection."
9 fi
View Code

 

2017/8/29

远程监控mysql

 1 #!/usr/bin/env bash
 2 #
 3 #Author:JACK ZHAO
 4 #DATE:2017/9/11
 5 #Description:Check the running status of mysql
 6 
 7 mysql -uroot -psf123456  -h 192.168.0.110 –P3306 -e "status" &>/dev/null
 8 if [ $? -eq 0 ];then
 9  echo "192.168.0.110_Mysql is runnging..."
10 else
11  echo "192.168.0.110_Mysql state exception."
12 fi
View Code

 

2017/8/28

打印杨辉三角

#!/usr/bin/env bash
#
# Author     : Jack zhao
# Date       : 2017/9/10
# Description: This script is used to printf the Yang hui triangle
if [ -z $1 ];then
  read -p "Please enter a number:" VAR
else
  VAR=$1
fi

a[0]=1

for ((i=0;i<=$VAR;i++));do
   for((j=$i;j>0;j--));do <--由后往前加,到a[0]为止
    a[$j]=$[a[$j]+a[$j-1]] 
   done 
  for  ((j=0;j<=$i;j++));do
      echo -n  " ${a[$j]}"
  done
  echo 
done
View Code

 

2017/8/27

打印99乘法表

 

#!/usr/bin/env bash
#
# Author    : Jack zhao
# Date      : 2017/9/10
# Description: This script is implemented,Yang multiplication table.
[ "$1" == "-h" ] || [ "$1" == "--help" ] && echo -e "sh `basename $0` \nDescription:printf Yang multiplication table " && exit 1
declare -i i j

for((i=1;i<=9;i++));do
  for((j=1;j<=$i;j++));do
    SUM=$[$j*$i]
    printf "%-8s" "${j}*${i}=${SUM}"
  done
echo  
done
View Code

 

 

 

2017/8/26 

1 编写一个名为iffile程序,它执行时判断/bin目录下date文件是否存在?
2 编写一个名为greet的问候程序,它执行时能根据系统当前的时间向用户输出问候信息。设从半夜到中午为早晨,中午到下午六点为下午,下午六点到半夜为晚上。

 1 1.
 2 #!/usr/bin/env bash
 3 #
 4 FILE=/bin/date
 5 if [ -e "$FILE"  ];then
 6   echo "$FILE exist."
 7 else
 8   echo "$FILE Non-existent."
 9 fi
10 
11 2.
12 #!/usr/bin/env bash
13 #
14 
15 CURRENT_TIME=`date +%H`
16 
17 
18 if [ $CURRENT_TIME -ge 0  -a $CURRENT_TIME -lt 12 ];then
19   echo "Good morning."
20 elif [ $CURRENT_TIME -ge 12 -a $CURRENT_TIME -lt 18 ];then
21   echo "Good afternoon."
22 else
23   echo "Good evening."
24 fi
View Code

2017/8/25  写一个shell脚本,检查指定的shell脚本是否有语法错误,若有错误,首先显示错误信息,然后提示用户输入q或者Q退出脚本,输入其他内容则直接用vim打开该shell脚本。提醒: 检查shell脚本有没有语法错误的命令是 sh -n xxx.sh

 1 #!/bin/bash
 2 #
 3 
 4 # Author       : Jack Zhao
 5 # DATE         : 2017/8/28
 6 # Descriptions : This script is used to detect whether other shell scripts have syntax errors
 7 
 8 Usage(){
 9  echo "Usage: `basename $0` [ARG]"
10  echo "Descriptions:This script is used to detect whether other shell scripts have syntax errors"
11 }
12 
13 [ $# -lt 1  ] && Usage && exit 1
14 [ $1 == "--help" ] && Usage && exit 0
15 [ ! -e  $1 ] && echo "$1 Non-existent." &&  exit 2
16 
17  bash -n $1 2> error.temp  
18 
19 if [ $? -ne 0  ];then
20   echo -e "\033[31;1m###This script has syntax errors###\033[0m" 
21   cat error.temp
22   read -p "Please enter the something[q|Q:exit]:" choice
23   case $choice in
24   q|Q)
25    exit 0 
26    ;;
27   *)
28    vim $1
29   ;;
30   esac
31 else
32  echo "$1 There is no syntax error"
33 fi
34 
35 rm  -rf error.temp
View Code

2017/8/24 写一个shell脚本,把192.168.0.0/24网段在线的ip列出来。
思路: for循环, 0.1 -- 0.254 依次去ping,能通说明在线。

 1 #!/bin/bash
 2 #
 3 
 4 # Author      : Jack Zhao
 5 # Date        : 2017/8/26
 6 # Description : This script is used to detect whether the IP address of 192.168.0.0/24 is online
 7 
 8 IP_START=192.168.0
 9 GREEN="\033[32m"
10 END="\033[0m"
11 
12 usage(){
13 echo "Usage: sh `basename $0`"
14 echo "Descriptions: This script is used to detect whether the IP address of 192.168.0.0/24 is online"
15 }
16 
17 [ "$1" == "--help" ] && usage && exit 0
18 for((i=1;i<=254;i++));do
19   ping ${IP_START}.$i -w 2 -c 2  &> /dev/null
20   if [ $? -eq 0 ];then
21     echo -e "$IP_START.$i ${GREEN}online${END}."
22   fi
23 done
View Code

2017/8/23 把一个文本文档中只有一个数字的行给打印出来。

 1 #!/bin/bash
 2 # Author      : Jach zhao
 3 # Date        : 2017/08/23
 4 # Description : This is scripts for gets a single row of Numbers in the file.
 5 
 6 Usage(){
 7  echo "Usage:`basename $0` [ARG] "
 8  echo "Descriptin: This is scripts for gets a single row of Number in the file."
 9 }
10 
11 
12 
13 [ $# -lt 1 ] && Usage && exit 0
14 [ "$1" == "--help" ] && Usage && exit 0
15 [ ! -e $1 ] && echo "$1 Non-existent,Please check." && exit 1
16 [ ! -r $1 ] && echo "$1 No read permission,Please check." && exit 2
17 
18 while read line;do
19  count=`echo -n  $line | sed 's@[^[:digit:]]@@g' | wc -c`
20  [ $count -eq 1 ] && echo $line
21 done < $1
View Code

2017/8/22 实现一个抽签脚本

1、写一个脚本执行后,输入名字,产生随机数01-99之间的数字。
2、如果相同的名字重复输入,抓到的数字还是第一次抓取的结果,
3、前面已经抓到的数字,下次不能在出现相同数字。
4、第一个输入名字后,屏幕输出信息,并将名字和数字记录到文件里,程序不能退出
继续等待别的学生输入。

 1 #!/bin/bash
 2 # Author      : Jack Zhao
 3 # Date        : 2017/8/22
 4 # Descprition : This script Draw lots between 01 and 100.
 5 
 6 declare -a ARRAY
 7 declare -i count=0
 8 R="\033[31;1m"
 9 N="\033[0m"
10 [ ! -e var_conf.temp ] && touch var_conf.temp
11 
12 random_num(){
13   while true;do
14     LUCKNUM=`echo $RANDOM | awk -F "" '{print$2$3}'`
15     ! `cat var_conf.temp | awk -F "=" '{print$2}' | grep -q $LUCKNUM` &&  break 
16   done
17 }
18 
19 recycle(){
20   rm  -rf  var_conf.temp 
21   unset ARRAY
22 }
23 
24 
25 Usage(){
26  echo "Usage: sh `basename $0`"
27  echo "This script for draw lots between 01 and 100"
28 
29 }
30 
31 [ "$1"  == "--help" ] && Usage && exit 0
32 while true;do
33   declare -i flag=0
34   read -p "Please enter your name or q exit:" NAME
35   [ "$NAME" == "q" ]  && recycle &&  exit 0 
36   [ -z `echo $NAME` ]  && continue
37   if [ ${#ARRAY[*]} -eq 0 ];then
38      random_num
39      echo -e  "Congratulations $R$NAME$N,Your lucky numbers is $R$LUCKNUM$N."
40      ARRAY[$count]=$NAME
41      echo "$NAME=$LUCKNUM" >> var_conf.temp
42      let count++
43   else
44     for((i=0;i<${#ARRAY[*]};i++));do
45       [ "${ARRAY[$i]}" == "$NAME" ] && flag=1 && break
46     done
47     if [ $flag -eq 1 ];then 
48       ESIXT_NUM=`cat var_conf.temp | grep -w "$NAME" | awk -F "=" '{print$2}'`
49       echo -e  "You have drawn lots,and your number is $R$ESIXT_NUM$N,Please Next one."
50     else 
51       random_num
52       echo -e "Congratulations $R$NAME$N,Your lucky numbers is $R$LUCKNUM$N."
53       ARRAY[$count]=$NAME
54       echo "$NAME=$LUCKNUM" >> var_conf.temp 
55       let count++
56     fi
57   fi
58 
59 done
View Code

2017/8/19 在服务器上,写一个监控脚本。
1. 每隔10s去检测一次服务器上的httpd进程数,如果大于等于500的时候,就需要自动重启一下apache服务,并检测启动是否成功?
2. 若没有正常启动还需再一次启动,最大不成功数超过5次则需要理解发邮件通知管理员,并且以后不需要再检测!
3. 如果启动成功后,1分钟后再次检测httpd进程数,若正常则重复之前操作(每隔10s检测一次),若还是大于等于500,那放弃重启并需要发邮件给管理员,然后自动退出该脚本。假设其中发邮件脚本为之前咱们使用的mail.py

 1 #!/bin/bash
 2 #
 3 APACHEPATH=/usr/sbin/apachectl
 4 IP=`ifconfig eth0 | grep "inet addr" | awk -F: '{print$2}' | cut -d" " -f1`
 5 declare -i i
 6 
 7 checkagain()
 8 {
 9   sleep 60
10   PROCS=`ps -ef | grep -i "httpd" -c`
11   [ $PROCS -gt 500 ] && echo "Apache httpd restart finished,but the pros gt 500.Please Check." | mail -s "Apache httpd Monitoring ($IP)" zcm_mail@126.com  && exit 0
12   main
13 }
14 
15 restarthttpd()
16 {
17  for ((i=1;i<=5;i++)) do
18    $APACHEPATH restart &> /dev/null
19    [ $? -eq 0 ] && echo "Apache httpd restart finished." | mail -s "Apache httpd Monitoring ($IP)" zcm_mail@126.com && checkagain
20  done
21  echo "Apache httpd restart failed." | mail -s "Apache httpd Monitoring ($IP)" zcm_mail@126.com && exit  110
22 }
23           
24 main(){  
25  while :; do
26   PROCS=`ps -ef | grep -i "httpd" -c` 
27   [ $PROCS -gt 500 -o $PROCS -eq 0 ] && restarthttpd 
28   sleep 10
29  done        
30 }     
31 
32 main
View Code

2017/8/18 创建一个函数,能接受两个参数:

1)第一个参数为URL,即可下载的文件;第二个参数为目录,即下载后保存的位置;
2)如果用户给的目录不存在,则提示用户是否创建;如果创建就继续执行,否则,函数返回一个51的错误值给调用脚本;
3)如果给的目录存在,则下载文件;下载命令执行结束后测试文件下载成功与否;如果成功,则>返回0给调用脚本,否则,返回52给调用脚本;

提示,在函数中返回错误值给调用脚本,使用return

 1 #!/bin/bash
 2 # 
 3 # Author      : JACK ZHAO
 4 # Date        : 2017/8/18
 5 # Descriptions: Scripts for downloading
 6 
 7 Usage(){
 8   echo "Usage:`basename $0` [URL] [Directory]"
 9   echo "Examples:"
10   echo "  `basename $0` http://mirrors.hust.edu.cn/centos/7/isos/x86_64/CentOS-7-x86_64-DVD-1611.iso /tmp"
11 }
12 
13 [ $# -ne 2 ] && Usage && exit 1
14 
15 download()
16 {  
17   if [ -d $2 ];then
18      ! wget &>/dev/null &&  yum  -y install wget &>/dev/null
19      if `wget -T 5  --spider $1 &>/dev/null`;then
20         echo "Start the download..."
21         wget -T 5  -P "$2" "$1" -o wget.log
22         ORIGINAL_SIZE=`grep "^Length" wget.log | awk  '{print$2}'`
23         DOWNLOAD_FILE=`grep "^Saving" wget.log | awk -F: '{print$2}'| sed 's@^..@@g'|sed 's@.$@@g' `        
24         DOWNLOAD_SIZE=`cat $DOWNLOAD_FILE | wc -c` 
25         if [ -e  $DOWNLOAD_FILE  ] && [ $ORIGINAL_SIZE -eq $DOWNLOAD_SIZE ];then
26           echo "Download successful"
27           return 0
28         else
29           echo "Download failed, please check"
30           return 52
31         fi
32      else
33        echo "$1 is a Invalid link,Please check again."
34        return 53
35      fi
36   else 
37      read -p "[$2 It doesn't exist, it's going to be created? y/n]:" CHOICE
38      if [ $CHOICE == "n" ];then
39        echo "You've pulled out of the script"
40        return 51
41      else
42        mkdir -p $2 && download $1 $2
43      fi
44   fi
45 } 
46   
47 download $1 $2 
View Code

2017/8/17  脚本的功能:脚本可以带参数也可以不带,参数可以有多个,每个参数必须是一个目录,脚本检查参数个数,若等于0,则列出当前目录本身;否则,显示每个参数包含的子目录。

 1 #!/bin/bash
 2 #
 3 
 4 if [ $# -eq 0 ];then
 5   echo "##### Current directory listing ##### "
 6   ls -ld  `pwd`
 7 else
 8   for i in "$@";do
 9     if [ -d "$i"  ];then
10      echo -e  "#####\033[32m$i's subdirectories\033[0m#####"
11      ls  -R "$i" | grep '^/' | sed 's/:$//g'
12     else
13      echo -e  "#####\033[32m$i's subdirectories\033[0m#####"
14      echo -e  "\033[31mDirectory does not exist.\033[0m"
15     fi
16   done
17 fi
View Code

2017/8/16  提示用户输入网卡的名字,然后我们用脚本输出网卡的ip。 看似简单,但是需要考虑多个方面,比如我们输入的不符合网卡名字的规范,怎么应对。名字符合规范,但是根本就没有这个网卡有怎么应对。

 1 #!/bin/bash
 2 #
 3 
 4 read -p "Get Ip for rhel6,Please Enter:[ethX | quit]:" MYETH
 5 NETWORK_HOME="/etc/sysconfig/network-scripts/"
 6 ETH_COUNT=`ls ${NETWORK_HOME}ifcfg-eth* | grep -c "$MYETH"` 
 7 
 8 if [ $ETH_COUNT -eq 0  ];then
 9   echo "$MYETH No exists."
10 else
11  echo -e  "$MYETH:\n`ip add show  $MYETH  | grep "\<inet\>" | awk -F "[/|/t]" '{print$2}'`"
12 fi
13 
14 [root@localhost ~]# ./816.sh   
15 Get Ip for rhel6,Please Enter:[ethX | quit]:eth0
16 eth0:
17 192.168.0.107
18 192.168.0.112
19 192.168.0.113
View Code

2017/8/15  写一个脚本,执行后,打印一行提示“Please input a number:",要求用户输入数值,然后打印出该数值,然后再次要求用户输入数值。直到用户输入"end"停止。

 1 #!/bin/bash
 2 #
 3 
 4 while true;do
 5 read -p "Please input a number or end:" NUMBER
 6   [ -z `echo $NUMBER` ] && echo "Please put in something,Try again." && continue
 7   [ $NUMBER == "end" ] && echo "You've quit."  && break
 8   if `echo $NUMBER | grep -q '[^0-9]'`;then
 9      echo "$NUMBER is not integer number.Please Try again."
10   else
11      echo "You put in number is :$NUMBER"
12   fi
13 done
View Code

2017/8/14  假设,当前MySQL服务的root密码为123456,写脚本检测MySQL服务是否正常(比如,可以正常进入mysql执行show processlist),并检测一下当前的MySQL服务是主还是从,如果是从,请判断它的主从服务是否异常。如果是主,则不需要做什么。 

View Code

2017/8/13  写一个脚本,检测你的网络流量,并记录到一个日志里,需要按照如下格式,并且一分钟统计一次(只需要统计外网网卡,假设网卡名字为eth0):

2017-08-04 01:11
eth0 input: 1000bps
eth0 output : 200000bps
###################
2017-08-04 01:12
eth0 input: 1000bps
eth0 output : 200000bps

 1 #!/bin/bash
 2 #
 3 while true;do
 4 sar -n DEV 1 60 > sar.demp
 5 
 6 RX=`egrep 'Average:.*eth0' sar.demp | awk '{print$5}'`
 7 SX=`egrep 'Average:.*eth0' sar.demp | awk '{print$6}'`
 8 
 9 RX_B=${RX%.*}
10 SX_B=${SX%.*}
11 
12 echo "##############" | tee -a /tmp/network.log
13 echo "`date +%F" "%H:%m`" | tee -a /tmp/network.log
14 
15 RX_BPS=`echo "$RX_B*8" | bc`
16 SX_BPS=`echo "$SX_B*8" | bc`
17 
18 echo "Eth0 input:$RX_BPS/bps"
19 echo "Eth0 ouput:$SX_BPS/bps"
20 done
View Code

2017/8/12  使用传参的方法写个脚本,实现加减乘除的功能。例如: sh a.sh 1 2,这样会分别计算加、减、乘、除的结果。

要求:
1 脚本需判断提供的两个数字必须为整数。
2 当做减法或者除法时,需要判断哪个数字大。
3 减法时需要用大的数字减小的数字。
4 除法时需要用大的数字除以小的数字,并且结果需要保留两个小数点。 

 1 #!/bin/bash
 2 #
 3 
 4 if [ $# -ne 2 ];then
 5   echo "Usage:`basename $0` parameter1 parameter2"
 6   echo "The operations of addition, subtraction, multiplication, and division of two positive integers."
 7   exit 1
 8 fi
 9 
10 if [ ! -z `echo $1 | sed 's@[[:digit:]]@@g'` ] || [ ! -z `echo $2 | sed 's@[[:digit:]]@@g'` ];then
11   echo "Argument must be positive integer."
12   exit 2
13 fi
14 
15 SUM=$[$1+$2]
16 printf "%-10s %-10s\n" SUM: "$1 + $2 = $SUM"
17 
18 if [ $1 -ge $2  ];then
19   SUBTRACT=$[$1-$2]
20   printf "%-10s %-10s\n" Subtract: "$1 - $2 = $SUBTRACT"
21 else 
22   SUBTRACT=$[$2-$1]
23   printf "%-10s %-10s\n" Subtract: "$2 - $1 = $SUBTRACT"
24 fi
25 
26 MULTIPLY=$[$1*$2]
27 printf "%-10s %-10s\n" Multiply: "$1 * $2 = $MULTIPLY"
28 
29    
30 if [ $1 -ge $2  ];then
31   DIVIDE=`echo "scale=2;$1/$2" | bc`
32   printf "%-10s %-10s\n" Subtract: "$1 / $2 = $DIVIDE"
33 else 
34   DIVIDE=`echo "scale=2;$2/$1" | bc`
35   printf "%-10s %-10s\n" Subtract: "$2 / $1 = $DIVIDE"
36 fi
View Code

2017/8/11 要求如下:
1.只支持三个选项 ‘--del’ ‘--add’ --help输入其他选项报错。
2.使用‘--add’需要验证用户名是否存在,存在则反馈存在。且不添加。 不存在则创建该用户,切添加与该用户名相同的密码。并且反馈。
3.使用‘--del’ 需要验证用户名是否存在,存在则删除用户及其家目录。不存在则反馈该用户不存在。
4.--help 选项反馈出使用方法
5.支持以,分隔 一次删除多个或者添加多个用户。
6.能用echo $? 检测脚本执行情况 成功删除或者添加为0,报错信息为其他数字。
7.能以,分割。一次性添加或者 删除多个用户。 例如 adddel.sh --add user1,user2,user3.......
8.不允许存在明显bug。

 1 #!/bin/bash
 2 #
 3 
 4 Usage()
 5 {
 6 cat <<  EOF
 7 Usage:useradmin [--add|--del|--help]
 8 eg:
 9    useradmin --add user1,user2,...
10    useradmin --del user1,user2,...
11    useradmin --help
12 EOF
13 }
14 
15 myuseradd(){
16 USERS=`echo $1 | awk -F "," '{for(i=1;i<=NF;i++)printf("%s\n",$i)}'`
17   for i in $USERS;do
18     if `id $i &>/dev/null`;then
19       echo "User:$i Already exists."
20    else
21       useradd $i &&  echo "$i"| passwd --stdin $i &>/dev/null
22       if [ $? -eq 0 ];then
23         echo "User:$i Add success."
24       else
25         echo "User:$i Add failed."
26         return 1;
27       fi
28    fi
29  done
30  return 0;
31 }
32 
33 myuserdel(){
34   USERS=`echo $1 | awk -F "," '{for(i=1;i<=NF;i++)printf("%s\n",$i);print""}'`
35   for i in $USERS;do
36     if ` ! id $i &>/dev/null`;then
37       echo "User:$i No exists."
38     else
39       userdel -r $i
40       if [ $? -eq 0 ];then     
41          echo "User:$i Delete success."
42       else
43          echo "User:$i Delete failed."
44          return 1;
45       fi
46     fi
47   done
48   return 0;
49 }
50 
51 [ ! -z `echo -e $2|sed 's@[[:alnum:],]@@g'` ] && echo "ERROR:User names must be numbers and letters or combinations of them" && Usage && exit 1;
52 case $1 in
53 --add)
54   myuseradd $2
55   ;;
56 --del)
57   myuserdel $2
58   ;;
59 --help)
60   Usage
61   exit 0;
62   ;;
63 *)
64   Usage
65   exit 1;
66   ;;
67 esac
View Code

2017/8/10 要求如下:

假设,当前MySQL服务的root密码为123456,写脚本检测MySQL服务是否正常(比如,可以正常进入mysql执行show processlist),并检测一下当前的MySQL服务是主还是从,
如果是从,请判断它的主从服务是否异常。如果是主,则不需要做什么。

 1 #!/bin/bash
 2 #
 3 
 4 MYSQL_URL="mysql -uroot -p123456"
 5 MYSQL_PRO=`ps -ef | grep mysqld  | grep -v "grep" -c`
 6 if [ $MYSQL_PRO -gt 0 ];then
 7   $MYSQL_URL -e "show slave status \G"  > /tmp/slave.temp
 8   if [ `wc -l /tmp/slave.temp | awk '{print$1}'` -eq 0 ];then
 9     echo "MySQL is master,It is starting..."
10   else
11    SLAVE1=`grep "Slave_IO_Running" /tmp/slave.temp | awk -F ":" '{print$2}'`
12    SLAVE2=`grep '\<Slave_SQL_Running\>' /tmp/slave.temp | awk -F ":" '{print$2}'`
13      if [ $SLAVE1 == "Yes" -a $SLAVE2 == "Yes"  ];then
14        echo "Mysql is slave,Running normal."
15      else
16        echo "Mysql is slave,Running NO normal."
17      fi
18   fi
19 else
20   echo "MySQL service exception."
21 fi
22 rm  -rf /tmp/slave.temp
View Code

 

转载于:https://www.cnblogs.com/xiangtanglaojing/p/7355997.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值