Shell Chapter 4作业

1.ping主机测试,查看主机是否存活

#! /bin/bash
read -p "please input your ip address:" host
ping -c 2 -w 2 $host &> /dev/null
if [ $? -eq 0 ];then
    echo $host is running
else
    echo $host is not running
fi

 2.判断一个用户是否存在

#!/bin/bash
read -p "please input your username" user
if [ $? -eq 0 ]
then
    echo "the user you input is already exist"
else
    echo "the user you input is not exist"
fi

3.判断当前主内核版本是否为3,次版本是否大于10

#!/bin/bash
ver1=$( uname -srm | cut -d ' ' -f 2 | cut -d '.' -f 1)
ver2=$( uname -srm | cut -d ' ' -f 2 | cut -d '.' -f 2)
if [ "$ver1" -eq 3 -o "$ver2" -gt 10 ]
then
        echo "the main version is 3 and the subversion is greater than 10"
elif [ "$ver1" -eq 3 ]
  echo "the main version is 3 and the subversion isn't greater than 10"
then
        echo "the main version is not 3"
fi

4.判断vsftpd软件包是否安装,如果没有则自动安装

#! /bin/bash
vsftpd &> /dev/null
if [ $? -eq 0 ]
then 
    echo "vsftpd has been installed"
else
    echo "vsftpd hasn't been installed"
    yum -y install vsftpd
fi

5.判断httpd是否运行

#! /bin/bash
status='systemctl is-active httpd'
if [ "$status" = 'failed' ]
then
    echo "httpd is not active"
else
    echo "httpd is active"
fi

6.判断指定的主机是否能ping通,必须使用$1变量

#! /bin/bash
read -p "please input your ip address:" host
ping -c 2 -w 2 $host &> /dev/null
if [ $? -eq 0 ]
then
    echo "the ip address is available"
else
    echo "the ip address is not available"
fi

7.报警脚本,要求如下是当根分区空间小于20%即内存空间大于80%时向用户alice发送告警邮件,并配合crond每5分钟检查一次

#!/bin/bash
totalmem=$(free -m | tr -s " " | cut -d " " -f 2 | head -2 | tail -1)
usedmem=$(free -m | tr -s " " | cut -d " " -f 3 | head -2 | tail -1)
usedmemper=$(echo "scale=2;$usedmem/$totalmem*100" | bc)
totalroot=$(df | grep "/"$ |tr -s " " | cut -d " " -f 2)
usedroot=$(df | grep "/"$ |tr -s " " | cut -d " " -f 4)
freerootper=$(echo "scale=2;$usedroot/$totalroot*100" | bc)
v1=$(echo "usedmemper > 80" | bc)
v2=$(echo "freerootper < 20" | bc)
if [ $v1 -eq 1 ];then
  echo "内存已用空间大于80%" | mail -s "警告信息" alice
elif [ $v2 -eq 1 ];then
  echo "根分区剩余空间小于20%" | mail -s "警告信息" alice
else
  echo "正常使用"
fi

8.判断用户输入的是否是数字,如果是则判断该数字是否大于10

#! /bin/bash
read -p "plese input num :" num
expr  $num + 6  &> /dev/null
if [  $? -eq 0 ]
then
        if [ $num -gt 10 ]
        then
                echo "bingger 10"
        else
                echo "no bigger 10"
        fi
else
        echo " is not num"
fi

9.计算用户输入的任意两个整数的和、差、乘积、商、余数

    要求:a.判断用户输入的参数是否是两个,如果不是则给出提示

               b.判断用户输入的是否是整数,如果不是则给出提示并终止运行

#! /bin/bash
[ $# -ne 2 ] &&{
echo "usage: $0 num1 num2 "
exit 1
}
expr $1 + $2 + 10 &> /dev/null
if [ $? -ne 0];then
        echo "you must input two number"
        exit 2
fi
echo "a+b=$(($1+$2))"
echo "a-b=$(($1+$2))"
echo "a*b=$(($1*$2))"
echo "a/b=$(($1/$2))"
 
echo "a%b=$(($1%$2))"

       

     

        

猜你喜欢

转载自blog.csdn.net/AChain1117/article/details/125876963