SHELL脚本的编写

目录

1、判断当前磁盘剩余空间是否有20G,如果小于20G,则将报警邮件发送给管理员,每天检查一次磁盘剩余空间。 

2、判断web服务是否运行(1、查看进程的方式判断该程序是否运行

3、使用curl命令访问第二题的web服务,看能否正常访问,如果能正常访问,则返回web server is running;如果不能正常访问,返回12状态码。


1、判断当前磁盘剩余空间是否有20G,如果小于20G,则将报警邮件发送给管理员,每天检查一次磁盘剩余空间。 

创建test1.sh并编辑

[root@root ~]# vim test1.sh

#!/bin/bash
 
free_mb=$(free -m | grep Mem | tr -s " " | cut -d " " -f4 )
if [[  $free_mb -lt 20480 ]]
then
        echo "warning: The computer has $free_gb G of memory left ,Less than 20G" | mail -s "warning" root
else
        echo " warning: The computer has $free_gb G ,It is enough"
fi

安装邮件服务

[root@root ~]# yum install postfix -y

[root@root ~]# yum install s-nail -y

重启邮件服务

[root@root ~]# systemctl restart postfix.service

执行test1.sh

[root@root ~]# bash test1.sh

测试

SHELL脚本的编写_第1张图片

 做计划任务

[root@root ~]# vim /etc/crontab

SHELL脚本的编写_第2张图片

 2、判断web服务是否运行(1、查看进程的方式判断该程序是否运行

安装httpd服务

[root@root ~]# yum install httpd -y

创建test2.sh(查看进程)

[root@root ~]# vim test2.sh



#!/bin/bash
 
num=$(ps -ef | grep httpd | grep -v grep | wc -l)
if [ $num -ge 1 ]
then    
        echo "httpd is running"
else    
        systemctl restart httpd
        systemctl stop firewalld
fi

 测试

[root@root ~]# systemctl stop httpd
[root@root ~]# sh test2.sh 
[root@root ~]# sh test2.sh 
httpd is running

查看端口,继续在test2中修改

[root@root ~]# vim test2.sh

#!/bin/bash

num=$(ss -lntup  |  grep  80  | wc  -l)
if [ $num -ge 1 ]
then
        echo "httpd is running"
else
        systemctl restart httpd
        systemctl stop firewalld
fi

再进行测试

[root@root ~]# systemctl stop httpd
[root@root ~]# sh test2.sh 
[root@root ~]# sh test2.sh
httpd is running

3、使用curl命令访问第二题的web服务,看能否正常访问,如果能正常访问,则返回web server is running;如果不能正常访问,返回12状态码。

创建test3.sh并编辑

[root@root ~]# vim test3.sh

#!/bin/bash

curl -s 192.168.242.129 > /dev/null
if [[  $? = 0 ]]
then
        echo " web server is running"
else
        exit 12
fi

测试

[root@root ~]# bash test3.sh 
 web server is running
[root@root ~]# systemctl stop httpd.service 
[root@root ~]# bash test3.sh 
[root@root ~]# echo $?
12

你可能感兴趣的:(linux,运维,服务器)