三,shell脚本开发基本规范
1,/etc/init.d/functions 中的系统函数 action使用方法:
显示 xxxx,并且最右端显示 绿色的 OK字样:action "xxxx" /bin/true
显示 xxxx,并且最右端显示 红色的 FAILED字样:action "xxxx" /bin/false
2,使用脚本实现SSHD服务的启动、关闭和重新启动:
#!/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 $0 {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,如何将自定义脚本添加到chkconfig中,以便实现开机启动和关机停止的功能
0)将脚本拷贝到 /etc/init.d/ 下
1)脚本顶部增加 # chkconfig: 2345 20 60 # 2345 运行级别 20启动排名顺序(不要和现有的冲突) 60关闭排名顺序(不要和现有的冲突)
2)脚本顶部增加 # description: xxxxxx
3)chkconfig添加 脚本名:chkconfig --add xxxxx
4)chkconfig设置启动:chkconfig xxxxx on
查询:chkconfig --list xxxxxx #运行级别2345 显示on,其他级别显示off
备注:chkconfig的原理:ll /etc/rc.d/rc3.d/ | grep xxxx #启动或关闭服务后会生成不同的2个软连接文件指向到原始脚本
5,通过case实现不同选择显示不同水果,并用不同的背景色
#!/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 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 " 33[43;37m your select apple 33[0m" ;; 2) echo -e " 33[44;37m your select pear 33[0m" ;; 3) echo -e " 33[45;37m your select banana 33[0m" ;; *) echo -e " 33[46;37m your select cherry 33[0m" esac
6,使用脚本启动 rsync服务
#!/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 # 或者 kill -USR2 "/var/run/rsyncd.pid" #判断端口或服务不一定正确;工作中,推荐生成flag标识判断服务是否启动 action "rsync is stpped" /bin/true fi } case "$1" in start) start_rsyncd exit ;; stop) stop_rsyncd exit ;; restart) stop_rsyncd sleep 2 start_rsyncd exit ;; *)
echo "USAGE: $0 {start|stop|restart}" exit ;; esac
7,两种方法实现打印5次uptime信息
#!/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,防止脚本执行中断的方法
1) 脚本.sh &
2)screen命令
3)nohup 脚本.sh &
9,当前脚本在前台正在执行中,但是又不想停止执行(ctl + c),可以暂停当前脚本执行(ctl + z),然后放到后台执行 (bg)
10,jobs:查看后台执行的脚本或任务
11,fg + 编号:把当前在后台执行的脚本或任务 调出到前台
12,其他进程管理命令:
cronttab:设置定时;ps:查看进程;pstree:显示进程状态树;top:显示进程;nice:改变优先权;nohup:用户退出系统之后继续工作;
pgrep:查找匹配条件的进程;strace:跟踪一个进程的系统调用(使用场景:某个进程占用CPU特别高,可以通过 strace -p [PID进程号] 跟踪);ltrace:跟踪进程调用库函数的情况;vmstat:报告虚拟内存统计信息
13,充值10元钱,每发送一次短信花费1角5分,模拟手机发送短信,到余额小于1角5分时提示余额不足请充值
#!/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,统计apache的 access-xxx.log日志中每一行的访问字节数大小
读取文件的每一行有三种办法:
cat access-xxx.log | while read line
do
done
或者
while read line
do
done < access-xxx.log
或者
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,每隔10秒钟,使用rsync推送本地mysql-binlog文件到远程主机进行备份,要求以守护进程执行
#!/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下,开机启动
echo "/bin/sh xxxxx.sh &" >> /etc/rc.local
16,for 循环结构
for in [ x in xxxx ] #当[ x in xxxx ] 不写时等于 $@
do
done
或
for(expr1; expr2; expr3)
do
done
#使用for循环设置开机只启动5个服务
#!/bin/bash LANG=en for a in `chkconfig --list|awk '{print $1}'` do chkconfig $a off done for a in sshd rsyslog crond network sysstat do chkconfig $a on done
#批量创建10个html文件
for a in `seq 10`;do touch baby-${a}.html;done;
#批量将baby改为man,并将html修改为大写
for a in `ls *.html`;do mv $a "`echo $a|sed 's/baby/man/g'|sed 's/html/HTML/g'`";done
或者
for a in `ls *.html`;do mv $a "`echo $a|sed 's/baby(.*).html/man1.HTML/g'`";done
17,获得随机字符串的几个方法
#取随机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,写一个脚本,实现判断192.168.1.0/24网络里,在线用户的IP有哪些?(使用ping命令实现)
#!/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,写一个脚本,通过web访问日志(或网络连接数),通过IPTABLES屏蔽DDOS攻击的IP
#!/bin/bash VISITTIMES=5 VISITCOUNT=3 while true do awk '{print $1}' access.log | grep -v '^$' | sort | uniq -c >> /tmp/tmp.log
# 或判断网络连接数: netstat -an|grep EST | awk -F '[ :]+' '{print $6}' | sort | uniq -c >> /tmp/tmp.log
# netstat详细参数:http://www.cnblogs.com/tla001/p/6436192.html exec </tmp/tmp.log while read line do
ip=`echo $line | awk '{print $2}'` count=`echo $line | awk '{print $1}'` if [ $count -gt $VISITCOUNT ] && [ `iptables -L -n | grep $ip | wc -l` -lt 1 ]; then iptables -I INPUT -s $ip -j DROP # 重启iptables失效 echo "$line is dropped " >> /tmp/droplist.log fi done sleep $VISITTIMES done
20,打印CHKSTR中单词不大于6的单词
#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,监控MYSQL主从同步是否异常,如果异常则发送短信或邮件给管理员
*************************** 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 # 和主库比同步延迟的秒数,这个参数很重要 Master_SSL_Verify_Server_Cert: No Last_IO_Errno: 0 Last_IO_Error: Last_SQL_Errno: 0 Last_SQL_Error:
阶段1:开发一个守护进程脚本每隔30秒实现检测一次 (使用文件模拟主从)
#!/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
阶段2:如果同步出现如下错误号(1158,1159,1008,1007,1062),请跳过错误,进行修复。( 使用主从环境 )
#!/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 statusG" | 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,开发LINUX一键优化脚本 【见视频:86 - 7】
01,安装系统时精简安装包(最小化安装)
02,配置国内高速yum源
03,禁用开机不需要启动的服务
04,优化系统内核参数 /etc/sysctl.conf
05,增加系统文件描述符、堆栈等配置
06,禁止root远程登录,修改SSH端口为特殊端口,禁止DNS,空密码
07,有外网IP的机器要开启配置防火墙,仅对外开启需要提供服务的端口,配置或关闭SELINUX
08,清除无用的默认系统账户或组(非必须)(添加运维成员的用户)
09,锁定敏感文件,如 /etc/passwd(非必须)
10,配置服务器和互联网时间同步
11,配置sudo对普通用户权限精细控制
12,配置系统字符集
13,把以上12点写成一键优化脚本
。。。。。。更多优化后面还会将的。。。
23,数组(只掌握定义和查找读取,增删改用得少)
1)数组的定义 : array=(1 2 3)
2)获取数组的长途: echo ${#array[@]} 或者 echo ${#array[*]}
3)打印数组元素 : echo ${array[下标]} # 下标从0开始
4)一次打印出全部数组:echo ${array[@]} 或者echo ${array[*]}
5)删除整个数组: unset array
6)删除指定下标的元素:unset array[下标]
7)数组截取: echo ${array[@]:2:3} #从数组的第2个元素开始,取3个元素,,类似字符串截取:aaa="123456"; echo ${aaa:2:3}
8)数组元素替换: echo ${array[@]/5/6} #将下标为5的元素值替换为6,并打印
9)工作中常用举例: array=($(ls))等
24,开发脚本监控文件变化情况,并实现定时检查 【教程:87--15】
1)每天只能上传一次文件
2)上传完成后,将要监控的文件,生成MD5指纹库到指定文件: 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)使用md5sum -c命令检查指纹库变化情况:md5sum -c /data/logs/md5sum.db
./.bash_logout: OK ./tongji_log.sh: OK ./autoservice.sh: OK ./down.log: OK
4)配合diff,wc -l等命令实现文件增加、减少、修改等信息的检查 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|