shell练习

一.判断当前磁盘空间是否有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

shell练习_第1张图片

三、使用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.

shell练习_第2张图片

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