Three, Shell script Development Basic Specification
System functions in 1,/etc/init.d/functions action using the method:
Show XXXX, and the right side shows the green OK Word: action "xxxx"/bin/true
Display XXXX, and the right side shows the red failed Word: Action "xxxx"/bin/false
2. Use scripts to start, shut down, and restart the SSHD service:
#!/bin/bash
[-f/etc/init.d/functions] && source/etc/init.d/functions
Cmd=$1
#parameter number
If [$#-ne 1-o "$cmd"! = "Start"-a "$cmd"! = "Stop"-a "$cmd"! = "Restart"]
Then
echo "USAGE $ {Start|stop|restart}"
Exit 1
Fi
#start
If ["$cmd" = = "Start"]
Then
/etc/init.d/sshd Start &>/dev/null
Sleep 1
Action "Starting sshd"/bin/true
Exit 0
Fi
#stop
If ["$cmd" = = "Stop"]
Then
/etc/init.d/sshd Stop &>/dev/null
Sleep 1
Action "Stopping sshd"/bin/true
Exit 0
Fi
#restartif [$]
If ["$cmd" = = "Restart"]
Then
Killall sshd
/etc/init.d/sshd Start &>/dev/null
Sleep 1
Action "Restarting sshd"/bin/true
Exit 0
Else
Exit 1
Fi
3. How to add a custom script to the Chkconfig for power-on start-up and shutdown stop function
0) Copy the script to/etc/init.d/
1) Add # chkconfig:2345 on top of script # 20 60 # 2345 Run level 20 start rank order (do not conflict with existing) 60 close rank order (do not conflict with existing)
2) Add # description:xxxxxx on top of script
3) chkconfig Add script name: Chkconfig--add xxxxx
4) chkconfig Setup start: Chkconfig xxxxx on
Query: Chkconfig--list xxxxxx #运行级别2345 display on, other levels show off
Remark: Principle of Chkconfig: ll/etc/rc.d/rc3.d/| grep xxxx #启动或关闭服务后会生成不同的2个软连接文件指向到原始脚本
5, through case to achieve different choices to display different fruits, and with a different background color
#!/bin/bash
Cat <<eof
1.apple
2.pear
3.banana
4.cherry
EOF
read-t 5-p "pls Input your choice: "A
expr $a + 0 &>/dev/null
If [$?] -ne 0]; Then
echo "pls input a integer"
exit 1
Fi
If [-Z "$a"]
then
&nbs P echo "pls input choice"
exit 2
Fi
If [$a-ne 1-a $a-ne 2-a $a-ne 3 -a $a-ne 4]
then
echo ' pls input right choice '
exit 3
Fi
Case "$a" in
1)
ECHO-E "\033[43;37m your Select apple\033[0m"
;;
2)
ECHO-E "\033[44;37m your Select pear\033[0m"
;
3)
ECHO-E "\033[45;37m your Select banana\033[0m"
;
*)
ECHO-E "\033[46;37m your Select cherry\033[0m"
Esac
6. Use a script to start the Rsync service
#!/bin/bash
. /etc/init.d/functions
START_RSYNCD () {
S= ' lsof-i:873 | Wc-l '
If [$s-ge 1]
Then
echo "Rsync has running"
Exit
Else
Rsync--daemon
Sleep 2
Action "Rsync is started"/bin/true
Fi
}
STOP_RSYNCD () {
S= ' lsof-i:873 | Wc-l '
If [-Z $s]
Then
echo "Rsync has stopped"
Exit
Else
Killall rsync &>/dev/null # or KILL-USR2 "/var/run/rsyncd.pid" #判断端口或服务不一定正确; at work, it is recommended to generate flag identification to determine whether the service is started
Action "Rsync is stpped"/bin/true
Fi
}
Case "$" in
Start
Start_rsyncd
Exit
;;
Stop
Stop_rsyncd
Exit
;;
Restart
Stop_rsyncd
Sleep 2
Start_rsyncd
Exit
;;
*)
echo "USAGE: $ {Start|stop|restart}"
Exit
;;
Esac
7, two methods to achieve the printing of 5 times uptime information
#!/bin/bash
Maxtime=5
While [$maxtime-ne 0]
Do
Uptime
Sleep 2
maxtime=$ ((maxtime-1))
Done
#!/bin/bash
Maxtime=5
While [$maxtime-ne 0]
Do
Uptime
Sleep 2
Maxtime= ' echo $maxtime-1 | BC '
Done
8. Ways to prevent script execution from breaking
1) script. Sh &
2) Screen command
3) nohup script. Sh &
9, the current script in the foreground is executing, but do not want to stop execution (CTL + c), you can pause the current script execution (ctl + z), and then put in the background execution (BG)
10,jobs: View scripts or tasks executed in the background
11,FG + Number: Bring the script or task currently executing in the background to the foreground
12, other process management commands:
Cronttab: Set timing; PS: view process; Pstree: Show process status tree; top: show process; nice: change priority; Nohup: Continue to work after the user exits the system;
Pgrep: The process of finding matching criteria; STRACE: Tracking system calls for a process (usage scenario: a process that consumes a high CPU and can be traced by strace-p [PID process number]); Ltrace: Tracing the process call library function ; Vmstat: Reporting Virtual memory statistics
13, recharge 10 yuan, each send a short message cost 1.5 cents, analog phone to send SMS, to balance less than 1.5 cents when the balance is insufficient please recharge
#!/bin/bash
I=1
sum=1000
While [$sum-ge 15]
Do
sum=$ ((sum-15))
echo "$i-send a message OK, balance: $sum"
Usleep 200000
((i++))
Done
echo "Sum is lower 15fen, pls input"
14, statistics the size of the number of bytes accessed per row in Apache's Access-xxx.log log
There are three ways to read each line of a file:
Cat Access-xxx.log | While Read line
Do
Done
Or
While Read line
Do
Done < Access-xxx.log
Or
EXEC < Access-xxx.log
While Read line
Do
Done
#实现:
#!/bin/bash
I=0
Sum=0
While Read line
Do
I= ' echo $line |awk ' {print $17} '
If expr $i + 0 &>/dev/null #判断是否为整数
Then
((Sum=sum + i))
Fi
Done<access.example.log
echo "Sum: $sum"
15, every 10 seconds, using rsync to push local mysql-binlog files to the remote host for backup, requires the daemon to execute
#!/bin/bash
While True
Do
rsync-az/data/mysql-bin.* rsync_backup@192.168.1.9::backup--password-file=/etc/rsync.password &
Sleep 10
Done
#添加到 rc.local, boot up
echo "/bin/sh xxxxx.sh &" >>/etc/rc.local
16,FOR Cycle Structure
For in [x in XXXX] #当 [x in xxxx] is equal to $@ when not written
Do
Done
Or
for (EXPR1; expr2; expr3)
Do
Done
#使用for循环设置开机只启动5个服务
#!/bin/bash
lang=en
For a in ' Chkconfig--list|awk ' {print $} '
Do
Chkconfig $a off
Done
For a in sshd rsyslog Crond network Sysstat
Do
Chkconfig $a on
Done
#批量创建10个html文件
For a in ' seq ';d o touch baby-${a}.html;done;
#批量将baby改为man and modify the HTML to uppercase
For a in ' ls *.html ';d o mv $a "' echo $a |sed ' s/baby/man/g ' |sed ' s/html/html/g '";d One
Or
For a in ' ls *.html ';d o mv $a "' echo $a |sed ' s/baby\ (. *\). html/man\1.html/g '";d One
17, several methods of obtaining random strings
#取随机8位密码:
echo $RANDOM | md5sum | Cut-c 1-8
#使用openssl获得随机字符串
echo OpenSSL rand-base64 8/10 ...
#使用date获得随机数
echo Date +%s%n
#使用UUID
Cat/proc/sys/kernel/random/uuid
#使用expect配合mkpasswd命令
Mkpasswd-l 8
18, write a script to determine the 192.168.1.0/24 network, the online user's IP. (implemented using the ping command)
#!/bin/bash
For n in ' seq 254 '
Do
Ping-c2 192.168.1. $n &>/dev/null
If [$?-eq 0]
Then
echo "192.168.1. $n is up" >> Up.log
Else
echo "192.168.1. $n is down" >> down.log
Fi
Done
19, write a script, through the Web Access log (or network connection number), through the Iptables Shield DDoS attack IP
#!/bin/bash
Visittimes=5
Visitcount=3
While True
Do
awk ' {print '} ' Access.log | Grep-v ' ^$ ' | Sort | Uniq-c >>/tmp/tmp.log
# or determine the number of network connections: Netstat-an|grep EST | Awk-f ' [:]+ ' {print $6} ' | Sort | Uniq-c >>/tmp/tmp.log
# netstat detailed parameters: http://www.cnblogs.com/tla001/p/6436192.html
EXEC </tmp/tmp.log
While Read line
Do
Ip= ' echo $line | awk ' {print $} '
Count= ' echo $line | awk ' {print '} '
If [$count-gt $VISITCOUNT] && [' Iptables-l-n | grep $ip | wc-l '-LT 1]; Then
Iptables-i input-s $ip-j DROP # restart iptables fail
echo "$line is dropped" >>/tmp/droplist.log
Fi
Done
Sleep $VISITTIMES
Done
20. Print words that are not more than 6 words in Chkstr
#shell中获取字符串长度的7种方法: http://blog.csdn.net/jerry_1126/article/details/51835119
#!/bin/bash
Chkstr= "I am babyes teacher Welcome to Babyes Traning class."
For a in $CHKSTR
Do
If [${#a}-lt 7]; Then
Echo $a
Fi
Done
21, monitor MySQL master-slave synchronization is abnormal, if abnormal send sms or mail to the administrator
1. Row ***************************
Slave_io_state:queueing Master event to the relay log
master_host:172.18.16.22
Master_user:repl
master_port:3306
Connect_retry:60
master_log_file:mysql-bin.010362
read_master_log_pos:555176
relay_log_file:mysqld-relay-bin.004136
relay_log_pos:502564
relay_master_log_file:mysql-bin.010327
Slave_io_running:yes
Slave_sql_running:yes
Replicate_do_db:blog
replicate_ignore_db:
Replicate_Do_Table:blog.archives
Replicate_ignore_table:
Replicate_wild_do_table:
Replicate_wild_ignore_table:
last_errno:0
Last_error:
skip_counter:0
exec_master_log_pos:555176
relay_log_space:364216
Until_condition:none
Until_log_file:
until_log_pos:0
Master_ssl_allowed:no
Master_ssl_ca_file:
Master_ssl_ca_path:
Master_ssl_cert:
Master_ssl_cipher:
Master_ssl_key:
seconds_behind_master:0 # and the number of seconds the main cubby synchronizes delay, this parameter is important
Master_ssl_verify_server_cert:no
last_io_errno:0
Last_io_error:
last_sql_errno:0
Last_sql_error:
Phase 1: Develop a daemon script to detect once every 30 seconds (using file emulation master/slave)
#!/bin/bash
While True
Do
array= (' Egrep ' io_running| Sql_running| behind_master| Sql_errno "Master_slave.log | awk ' {print $NF} ')
If ["${array[0]}"! = "yes"-O "${array[1]}"! = "yes"-O "${array[2]}"! = "0"
Then
warning= "MySQL slave is not OK"
Echo $warning
echo $warning | Mail-s $warning 271810784@qq.com
Else
echo "MySQL slave is OK"
Fi
Sleep 30
Done
Phase 2: If the following error number (1158,1159,1008,1007,1062) appears in sync, skip the error and fix it. (using master-slave environment)
#!/bin/bash
errnoarray= (1158 1159 1008 1007 1062)
mysql_cmd= "Mysql-uroot-pbabyes-s/data/3307/mysql.sock"
While True
Do
Array= ($ ($mysql _cmd-e "show slave status\g" | egrep "Io_running| Sql_running| behind_master| Sql_errno "| awk ' {print $NF} '))
If ["${array[0]}"! = "yes"-O "${array[1]}"! = "yes"-O "${array[2]}"! = "0"
Then
For ((i=0;i<${#errnoarray [@]};i++))
Do
If ["${array[3]}" = = "${errnoarray[$i]}"]
Then
$mysql _cmd-e "Stop Slave;set global sql_slave_skip_counter=1;start slave;"
Fi
Done
warning= "MySQL slave is not OK"
Echo $warning
echo $warning | Mail-s $warning 271810784@qq.com
Else
echo "MySQL slave is OK"
Fi
Sleep 30
Done
22, develop Linux one-click Optimization Script "See Video: 86-7"
01. Compact installation package When installing the system (minimized installation)
02, configure the domestic high-speed Yum source
03. Disable boot-up service not required
04, optimize the system kernel parameter/etc/sysctl.conf
05, add configuration of System file descriptor, stack, etc.
06, disable root telnet, modify SSH port to special port, prohibit DNS, empty password
07, the machine with the network IP to open the configuration firewall, only to open the port to provide services, configure or close SELinux
08. Clear unused default system accounts or groups (not required) (Users who add OPS members)
09. Lock sensitive files, such as/etc/passwd (not required)
10. Configure server and Internet time synchronization
11, configure sudo fine control for normal user privileges
12, configuring the system character Set
13, write the above 12 points as a one-click Optimization script
。。。。。。 More optimizations will be later ...
23, Array (only master definition and lookup read, and delete and change to use less)
1) Definition of array: array= (1 2 3)
2) get an array of long distance: Echo ${#array [@]} or echo ${#array [*]}
3) Print array elements: Echo ${array[subscript]} # subscript starting from 0
4) Print out all arrays at once: Echo ${array[@]} or echo ${array[*]}
5) Delete the entire array: unset array
6) Delete the specified subscript element: unset array[Subscript]
7) Array intercept: Echo ${array[@]:2:3} #从数组的第2个元素开始, take 3 elements, similar to string interception: Aaa= "123456"; Echo ${aaa:2:3}
8) array element substitution: Echo ${ARRAY[@]/5/6} #将下标为5的元素值替换为6, and print
9) Common examples of work: array= (LS), etc.
24. Develop scripts to monitor file changes and implement timed checks "tutorial: 87--15"
1) Only one file can be uploaded once a day
2) After uploading the file to be monitored, generate the MD5 fingerprint library to the specified file: File/data/www/website-type f | Xargs md5sum >/data/logs/md5sum.db
6a5bc1cc5f80a48b540bc09d082b5855./.bash_logout
491259328caba7851914116c2f353123./tongji_log.sh
5cbf8812381683efb883d4b5697d6b6f./autoservice.sh
55e5d88002dd0cfeb86efa89340a7b9e./down.log
3) Use the MD5SUM-C command to check the change of the fingerprint library: md5sum-c/data/logs/md5sum.db
./.bash_logout:ok
./tongji_log.sh:ok
./autoservice.sh:ok
./down.log:ok
4) with diff,wc-l and other commands to achieve file additions, reductions, modifications and other information inspection