> 文章列表 > shell 初级

shell 初级

shell 初级

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

 [root@localhost ~]# bash c.sh
c.sh: line 7: echo剩余内存:1GB,小于20GB

判断web服务是否运行(1、查看进程的方式判断该程序是否运行,2、通过查看端口的方式判断该程序是否运行),如果没有运行,则启动该服务并配置防火墙规则。

先提前安装httpd包

[root@localhost ~]# yum install  -y httpd
查看进程的方法

编写脚本

 [root@localhost ~]#vim c2.sh

#!/bin/bash

vv=$(ps -ef |grep httpd |grep -v grep |wc -l)
if [[$vv > 0]];
then    
        echo "httpd.service is runing  "
else    
        systemctl start httpd
        systemctl stop firewalled
fi      

加上可执行的权限

[root@localhost ~]# chmod a+rx  c2.sh

结果:

[root@localhost ~]# bash c2.sh
httpd.service is runing  (需要注意的是脚本中名称尽量不要带有httpd字眼否则可能会影响进程数的判断)

查看端口

编写脚本

[root@localhost ~]# vim c3.sh

#!/bin/bash

pp=$(ss -lntup | grep -w 80 |wc -l)
if [[ $pp > 0 ]];
then
       echo "httpd is runing "
else
        systemctl start httpd
        systemctl stop firewalled
fi

给予权限

[root@localhost ~]# chmod a+rx  c3.sh

进行测试

[root@localhost ~]# bash c3.sh
httpd is runing 
 

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

编写代码

#!/bin/bash

[root@localhost ~]# vim c4.sh

#!/bin/bash
curl -s 12.168.9.130 > /dev/null
if [[ $? = 0]];
then    
        echo"web server is runing "
else    
        exit 12
fi      

给与权限

[root@localhost ~]# chmod a+rx  c4.sh
 

结果

[root@localhost ~]# bash c4.sh
12