SHELL脚本的编写
目录
1、判断当前磁盘剩余空间是否有20G,如果小于20G,则将报警邮件发送给管理员,每天检查一次磁盘剩余空间。
分析
创建脚本test1
下载邮件服务
执行
做计划任务
编辑- 2、判断web服务是否运行(1、查看进程的方式判断该程序是否运行,2、通过查看端口的方式判断该程序是否运行),如果没有运行,则启动该服务并配置防火墙规则。
查看进程方式:
创建脚本test2
测试
查看端口方式:
在test2脚本修改
测试
- 3、使用curl命令访问第二题的web服务,看能否正常访问,如果能正常访问,则返回web server is running;如果不能正常访问,返回12状态码。
编写脚本test3.sh
测试
1、判断当前磁盘剩余空间是否有20G,如果小于20G,则将报警邮件发送给管理员,每天检查一次磁盘剩余空间。
分析
首先使用df -m 命令查看剩余多少mb,使用if判断是否小于20g。发送邮件需要安装邮件服务器(安装服务端:yum install postfix -y ;安装客户端:yum install s-nail -y;每天检查则需要做一次计划任务
创建脚本test1
[root@server ~]# vim test1.sh#!/bin/bashfree_mb=$(free -m | grep Mem | tr -s " " | cut -d " " -f4 )
if [[ $free_mb -lt 20480 ]]
thenecho "warning: The computer has $free_gb G of memory left ,Less than 20G" | mail -s "warning" root
elseecho " warning: The computer has $free_gb G ,It is enough"
fi
下载邮件服务
[root@server ~]# yum install postfix -y
[root@server ~]# yum install s-nail -y
执行
[root@server ~]# sh test1.sh
测试
做计划任务
[root@server ~]# vim /etc/crontab
- 2、判断web服务是否运行(1、查看进程的方式判断该程序是否运行,2、通过查看端口的方式判断该程序是否运行),如果没有运行,则启动该服务并配置防火墙规则。
首先安装httpd
[root@server ~]# yum install httpd -y
查看进程方式:
创建脚本test2
[root@server ~]# vim test2.sh#!/bin/bashnum=$(ps -ef | grep httpd | grep -v grep | wc -l)
if [ $num -ge 1 ]
then echo "httpd is running"
else systemctl restart httpdsystemctl stop firewalld
fi
测试
[root@server ~]# systemctl stop httpd #先关闭服务
[root@server ~]# sh test2.sh #执行脚本开启服务
[root@server ~]# sh test2.sh #继续执行脚本
httpd is running
查看端口方式:
在test2脚本修改
[root@server ~]# vim test2.sh#!/bin/bashnum=$(ss -lntup | grep 80 | wc -l)
if [ $num -ge 1 ]
thenecho "httpd is running"
elsesystemctl restart httpdsystemctl stop firewalld
fi
测试
[root@server ~]# systemctl stop httpd #先关闭服务
[root@server ~]# sh test2.sh #执行脚本开启服务
[root@server ~]# sh test2.sh #继续执行脚本
httpd is running
- 3、使用curl命令访问第二题的web服务,看能否正常访问,如果能正常访问,则返回web server is running;如果不能正常访问,返回12状态码。
编写脚本test3.sh
[root@server ~]# vim test3.sh #!/bin/bashcurl -s 192.168.38.128 > /dev/null
if [[ $? = 0 ]]
thenecho " web server is running"
elseexit 12
fi
测试
[root@server ~]# sh test3.sh web server is running
[root@server ~]# systemctl stop httpd
[root@server ~]# sh test3.sh
[root@server ~]# echo $?
12