shell编程语句 函数 数组

mac2024-08-17  70

1.1if条件语句

企业案例:监控系统可用内存,小于100M就发送报警邮件 否则,提示内存充足,定时 任务每3分钟1次

分析项目: 1.取出当前内存 2.书写脚本 进行对比 3. 小于发邮件 4. 正常 提示正常 5. 定时任务

#!/bin/bash mem=$(free -m|awk 'NR==2{print $NF}') if [ "$mem" -lt "10000" ] then echo "mem is buzu" |tee /root/mem.log mail -s "memory is buzu" 918391635@qq.com </root/mem.log else echo "mem is zu" fi 温馨提示: +表示执行过程(命令) +越多越优先执行 没有加号 一般屏幕提示(输出 [root@m01 /server/scripts]# crontab -l |tail -2 #check memory at 20191111 by liyy * * * * * sh /server/scripts/04_01_chk_mem.sh &>/dev/null

1.2书写脚本 常用监控内容

目标使用的命令本地端口监控ss/netstat/lsof远端端口监控telnet/nc/nmap进程监控ps -ef/ps aux客户端模拟监控curl/wget数据库mysql -uroot -p123 -e “select version ();” nc参数-l指定处于监听模式-s指定发酥数据源ip地址-u指定nc使用udp协议,默tcp-w超时时间-z不发送任何数据-k用户断开.nc不断开nmap参数-p指定扫描的端口-sn检查主机是否运行ps参数-C指定进程名称-o按照格式输出–no-heading不输出标题curl参数-I大写只显示响应头信息-H修改请求头中信息-v显示详细信息-L跟随跳转,访问正确网站-s不显示头部信息-w按照指定格式输出-A指定浏览器-o输出写到指定文件-u指定登录用户名和密码wget参数-O下载到指定文件中-P下载到指定目录中–debug显示详细过程-t最大尝试次数-T超时时间-q静默模式–spider爬虫.只访问不下载-r下载整个页面top参数-p查看指定进程信息-H显示线程信息

1.3案例

rsync服务管理脚本

[root@oldboyedu-c6 ~]# cat /etc/init.d/rsyncd #!/bin/bash pid_file=/var/run/rsyncd.pid choice=$1 if [ "$choice" = "start" ] then if [ -s "$pid_file" ] then echo "rsync is running" else rsync --daemon fi elif [ "$choice" = "stop" ] then if [ -s "$pid_file" ] then kill `cat $pid_file` else echo "rsync has stopped" fi elif [ "$choice" = "restart" ] then [ -s "$pid_file" ] && kill `cat $pid_file` sleep 2 rsync --daemon else echo "Usage: $0 start|stop|restart" fi Centos6通过chkconfig 管理rsync chkconfig /serivce管理服务脚本的规则

脚本必须放在/etc/init.d/ 并且有执行权限

脚本的前几行 必须要有chkconfig要求的格式

# chkcofig: 2345 99 98 # chkconfig: 默认在2345 开机自启动 开机顺序 关机顺序

chkconfig --add rsyncd 加入到chkconfig管理

CentOS 7下面 systemctl 开机自启动

[root@m01 /usr/lib/systemd/system]# cat rsync-new.service [Unit] After=network.target [Service] Type=forking ExecStart=/server/scripts/rsyncd start ExecReload=/server/scripts/rsyncd restart ExecStop=/server/scripts/rsyncd stop [Install] WantedBy=multi-user.target

参考地址:

https://access.redhat.com/documentation/en-us https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html-single/system_administrators_guide/index

2.1函数

简介: 将程序里多次被调用的相同的代码组合起来(函数体),并取个名字(函数名)在脚本中 同1堆代码 被多次调用 这时候就使用函数为了凸显 脚本 专业/NB 特殊变量脚本函数$n脚本第n个参数函数第n个参数$0脚本名称脚本名称$*/$@脚本所有参数函数所有参数$#脚本参数个数函数参数个数

2.2案例

检测网站URL是否异常,利用函数及传参

[root@m01 scripts]# cat url.sh #!/bin/bash url=$1 function check () { [ -f /etc/init.d/functions ] && . /etc/init.d/functions [[ $url =~ [a-Z]+\.(com|xyz|cn|org)$ ]] || { echo -e "\e[1;32mUsage: $0 URL\e[0m" exit 5 } } function url () { curl=`curl -I -s -o /dev/null --connect-timeout 2 -w % {http_code} $url` if [ $curl -eq 200 ] then action "$url is tong" /bin/true else action "$url is faild" /bin/false fi } function main () { check url $url } main

3.1case语句

rsync启动脚本

[root@m01 /server/scripts]# cat rsyncd #!/bin/bash # chkconfig: 2345 99 98 pid_file=/var/run/rsyncd.pid choice=$1 start() { if [ -s "$pid_file" ] then echo "rsync is running" else rsync --daemon fi } stop() { if [ -s "$pid_file" ] then kill `cat $pid_file` else echo "rsync has stopped" fi } restart() { stop sleep 2 start } main() { case "$choice" in start) start ;; stop) stop ;; restart) stop sleep 2 start ;; *) echo "Usage:$0{start|stop|restart}" esac } main

4.1颜色

Linux命令行给字体加颜色命令为:

[root@oldboy scripts]# echo -e "\E[1;31m红色oldboy\E[0m" 红色字oldboy [root@oldboy scripts]# echo -e "\033[31m红色字oldboy \033[0m" 红色字oldboy

在上述命令中: 1.echo -e可以识别转义字符,这里将识别特殊字符的含义,并输出。 2.\E也可以使用\033替代。

[root@m01 /server/scripts]# cat color.sh #!/bin/bash red='\e[1;31m' green='\e[1;32m' blue='\e[1;34m' end='\e[0m' cat <<EOF ========== 1.input red 2.input green 3.input blue ========== EOF read input case "$input" in red) echo -e "${red}$input${end}" ;; green) echo -e "${green}$input${end}" ;; blue) echo -e "${blue}$input${end}" ;; *) echo "Usage: $0 {red|green|blue}" esac

5.1当型循环和直到型循环

名称(n为数字)含义continue n终止本次循环,进行下次循环break n终止循环(退出)exit n退出脚本return返回数值

5.2 循环练习题

while循环计算1+2+3…100累加

简单粗暴方法: [root@m01 scripts]# seq -s+ 100|bc 5050 [root@m01 scripts]# echo {1..100}+ 0|bc 5050 while方法: #!/bin/bash num=$1 i=0 chk_num() { if [[ ! "$num" =~ ^[0-9]+$ ]];then echo Usage: input number exit2 fi } p() { while [ $i -lt $num ] do ((i++)) ((sum=sum+i)) done echo $sum } main() { chk_num p } main

while read读取文件内容

[root@m01 /server/scripts]# cat read-file.sh #!/bin/bash file=stu.txt sum=0 while read line do age=`echo $line |awk '{print $3}' ` ((sum+=age)) done<$file echo $sum [root@m01 /server/scripts]# sh read-file.sh 131 [root@m01 /server/scripts]# cat stu.txt 01 oldtian 18 02 oldbao 98 03 oldnana 9 04 oldxialv 66

写一个Shell脚本解决类DDOS攻击的生产案例。请根据web日志或者或 者系统网络连接数,监控当某个IP并发连接数,若短时内PV达到100(阈值),即调用 防火墙命令封掉对应的IP。防火墙命令为:iptables -I INPUT -s IP地址 -j DROP

[root@web01 ~]# vim oldboy04.sh #!/bin/sh count=100 awk '{print $1}' /var/log/nginx/access.log-20190928 |sort|uniq -c|sort -nr -k1 >/tmp/tmp.log exec </tmp/tmp.log while read line do IP= $(echo $line|awk '{print $2}') if [ $(echo $line|awk '{print $1}') -ge $count ];then iptables -I INPUT -s $IP -j DROP fi done

for循环在/oldboy目录下通过随机小写10个字母加固定字符串oldboy批量创建10个html文件

[root@web01 ~]# vim oldboy.sh #!/bin/sh [ -d "/oldboy" ] || mkdir /oldboy for n in `seq 10` do random=$(echo $RANDOM|md5sum|tr "[0-9]" "[a-z]"|cut -c 2-11) touch /oldboy/${random}_oldboy.html done

批量创建10个系统帐号oldboy01-oldboy10并 设置密码(密码为随机8位字符串)

[root@web01 ~]# vim oldboy02.sh #!/bin/sh [ -f /etc/init.d/functions ]&& source /etc/init.d/functions for user in oldboy{01..10} do pass=$(echo $RANDOM|md5sum|cut -c 1-8) useradd $user && \ echo "$pass"|passwd --stdin $user >/dev/null if [ $? -eq 0 ];then action "Useradd $user IS OK" /bin/true fi echo “$user\t$pass” >>/tmp/user.txt done

写一个脚本,实现判断10.0.0.0/24网络里,当 前在线用户的IP有哪些(方法有很多)

[root@web01 ~]# vim oldboy03.sh #!/bin/sh source /etc/init.d/functions CMD="ping -W 2 -c 2" IP="10.0.0." for n in $(seq 254) do $CMD $IP$n >/dev/null if [ $? -eq 0 ];then action "$IP$n IS OK" /bin/true fi done

6.1shell数组

定义数组的方式

[root@m01 tmp]# arry[0]=old01 [root@m01 tmp]# arry[1]=old02 [root@m01 tmp]# echo ${arry[*]} old01 old02 [root@m01 tmp]# arry=(oldboy oldgirl oldbaby) [root@m01 tmp]# echo ${arry[*]} oldboy oldgirl oldbaby [root@m01 tmp]# arry=($(cat /etc/hosts)) [root@m01 tmp]# echo ${arry[*]} 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 10.0.0.5 lb01 10.0.0.6 lb02 10.0.0.7 web01 10.0.0.8 web02 10.0.0.9 web03 10.0.0.31 nfs01 10.0.0.41 backup 10.0.0.51 db01 10.0.0.61 m01 10.0.0.71 zabbix

最新回复(0)