shell练习

本文介绍了如何在Linux环境中监测磁盘空间,当低于20GB时通过smail发送报警邮件。同时,通过脚本检查Web服务状态,若未运行则自动启动服务并配置防火墙规则。此外,还展示了使用curl检查Web服务是否可达,根据返回状态确认服务器运行状况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.判断当前磁盘空间是否有20g,如果小于20g,则将报警邮件发送给管理员,每天检查一次磁盘剩余空间
1.安装smail
[root@server ~]# yum install s-nail -y
2.编辑配置文件
set from =123456789@qq.com
set smtp =smtp.qq.com
set smtp-auth-user=123456789@qq.com
set smtp-auth-password=nlakndsf
set smtp-aut=login
3.编写脚本
#!/bin/bash 

test_disk=`df -m | grep -w / | tr -s " " | cut -d " " -f4`
           
test_dir="warning disk space less than 20g"
              
if [ "$test_disk" -lt 20000 ]
then
        echo "$test_dir" | mail -s "$test_dir" 123456789@qq.com
fi  
4.设置定时
[root@server ~]# vim /etc/crontab
0 0 * * * root /bin/bash        /root/dist_script.sh
二、判断web服务是否运行

查看进程的方式判断是否运行
通过查看端口的方式判断是否运行
如果没有运行则启动该服务并配置防火墙规则

1.编写脚本
#!/bin/bash

service_name=`ps -ef | grep httpd | grep -v grep | wc -l`
if (($service_name>0))
then
    echo "httpd is already running"
else
    echo "httpd not started, waiting..."
    yum install httpd -y &> /dev/null
    systemctl start httpd
    systemctl start firewalld
    firewall-cmd --permanent --zone=public --add-service=http > /dev/null
    firewall-cmd --permanent --zone=public --add-port=80/tcp > /dev/null
    firewall-cmd --reload > /dev/null
    echo "httpd is already running"
fi
2.测试
[root@server ~]# bash test_web.sh 
httpd is already running

[root@server ~]# bash test_web.sh 
httpd not started, waiting...
Warning: ALREADY_ENABLED: http
Warning: ALREADY_ENABLED: 80:tcp
httpd is already running

image.png

三、使用curl命令访问第二题的web服务,看能否正常访问,如果正常访问,则返回 web server is running ,如果不能正常访问呢,则返回12状态
1.编写脚本
#!/bin/bash

ip_addr=`ip a | grep ens160 | grep inet | tr -s " " | cut -d " " -f3`
ip=${ip_addr%/*}

curl -s $ip > /dev/null
if (($?==0))
then
        echo    "web server is running."
else
        echo "web not accessible"
        exit 12
fi
2.测试脚本
[root@server ~]# bash test_curl.sh
web not accessible
[root@server ~]# systemctl restart httpd
[root@server ~]# bash test_curl.sh
web server is running.

image.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值