shell脚本之基础练习题(批量创建用户、99乘法表、检查软件是否安装、解决DOS攻击...)

    技术2022-07-11  84

    1、获取随机字符串或数字

    方法一: [root@centos ~]# vim random.sh #!/bin/bash function print_random() { for i in {1..10}; do echo -e "$i \t $RANDOM" done } print_random [root@centos ~]# sh random.sh 方法二:date随机数法 [root@centos ~]# vim date.sh #!/bin/bash a=`date +%s%N` echo $a [root@centos ~]# sh date.sh 方法三:通过内部系统变量 [root@centos ~]# echo $RANDOM 5173 [root@centos ~]# echo $RANDOM 9792

    2、定义一个颜色输出字符串函数

    [root@centos ~]# vim color.sh #!/bin/bash color(){ if [ $1 == "red" ] then echo -e "\033[31m$2\033[0m" elif [ $1 == "green" ] then echo -e "\033[32m$2\033[0m" elif [ $1 == "blue" ] then echo -e "\033[36m$2\033[0m" fi } color green "绿色" color red "红色" [root@centos ~]# sh color.sh 绿色 红色

    关于shell脚本字体颜色拓展

    3、批量创建用户

    #!/bin/bash read -p "please input passwd:" PASSWD for UNAME in `cat file4` do id $UNAME &> /dev/null if [ $? -eq 0 ] then echo "the $UNAME already exist" else useradd $UNAME &> /dev/null echo $PASSWD | passwd --stdin $UNAME &> /dev/null if [ $? -eq 0 ] then echo "$UNAME create sucessful" else echo "$UNAME create failed" fi fi done

    4、检查软件包是否安装

    rpm -ivh your-package # 直接安装 rpmrpm --force -ivh your-package``.rpm # 忽略报错,强制安 [root@localhost ~]# rpm -ql tree # 查询 [root@localhost ~]# rpm -e tree # 卸载 [root@localhost ~]# rpm -ql tree # 查询 #!/bin/bash read -p "input your rpm packet name:" i x=`rpm -qa | grep $i` if [ $? -eq 0 ] then echo "the packet already exist" else `yum install $i` fi

    5、检查服务状态

    方法一: 服务状态判断: 根据命令的返回值$?做判断

    #!/bin/bash `ps -ef |grep httpd |grep -v grep` &>/dev/null if [ $? -eq 0 ] then echo "httpd is up ..." else echo "httpd is down ..." fi

    方法二:

    netstat -tulanp |grep 80,ps -ef |grep httpd ;wc -l #判断数字

    6、检查主机存活状态

    while true do curl 127.0.0.1 &>/dev/null if [ $? -eq 0 ] then echo " ok..." else echo "not ok ..." fi sleep 1 done

    7、监控CPU、内存和硬盘利用率

    #!/bin/bash while true do echo "1.查看磁盘分区 2.CPU负载 3.剩余内存 4.退出" read -p "请输入你要执行的操作:>>>" num PART(){ #echo $HOSTNAME #fdisk l echo "hostname:$HOSTNAME" echo "system: `cat /etc/redhat-release`" #定义数组 array1=(`lsblk -l |awk '/sd[a-z][0-9]/{print $1}'`) array2=(`lsblk -l |awk '/sd[a-z][0-9]/{print $4}'`) array3=(`lsblk -l |awk '/sd[a-z][0-9]/{print $6}'`) array4=(`lsblk -l |awk '/sd[a-z][0-9]/{print $7}'`) #遍历数组 num=`echo $((${#array1[@]}-1))` for i in `seq 0 $num` #i=0 do cat <<EOF ---------${array1[$i]}----------- path: ${array1[$i]} size: ${array2[$i]} file_os: ${array3[$i]} mount_on:${array4[$i]} EOF done } case $num in 1) PART #echo "parting...." ;; 2) echo "loading..." ;; 3) echo "mem...." ;; 4) exit 0 ;; *) print "please input true list..." esac done

    8、批量主机磁盘利用率监控

    [root@centos ~]# lsblk -l #磁盘利用率 NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sda 8:0 0 20G 0 disk sda1 8:1 0 200M 0 part /boot sda2 8:2 0 10G 0 part / sda3 8:3 0 2G 0 part [SWAP] sr0 11:0 1 3.7G 0 rom /media [root@centos ~]# df -h #查看硬盘信息 Filesystem Size Used Avail Use% Mounted on /dev/sda2 9.8G 952M 8.3G 11% / tmpfs 491M 0 491M 0% /dev/shm /dev/sda1 190M 30M 150M 17% /boot /dev/sr0 3.7G 3.7G 0 100% /media

    df -h:查看硬盘信息 sed ‘1d’:删除第一行 awk ‘{print $5}’:打印第5列 sed ‘s/%//g’ :将%替换成空,g是全局的意思。 sed -n 1p:显示修改(-n选项)的第一行 a1-4是检查磁盘分区信息

    a1=$(df -h|sed '1d'|awk '{print $5}'|sed 's/%//g'|sed -n 1p) a2=$(df -h|sed '1d'|awk '{print $5}'|sed 's/%//g'|sed -n 2p) a3=$(df -h|sed '1d'|awk '{print $5}'|sed 's/%//g'|sed -n 3p) a4=$(df -h|sed '1d'|awk '{print $5}'|sed 's/%//g'|sed -n 4p)

    b1-4是把分区名过滤出来

    b1=$(df -h|sed 1d|awk '{print $1}'|sed -n 1p) b2=$(df -h|sed 1d|awk '{print $1}'|sed -n 2p) b3=$(df -h|sed 1d|awk '{print $1}'|sed -n 3p) b4=$(df -h|sed 1d|awk '{print $1}'|sed -n 4p)

    当前日期(年-月-日 时:分:秒) DAY=$(date +%F\ %T)

    #判断使用率,大于(-gt)80就记录日志. if [ $a1 -gt 89 ];then echo "$DAY $b1 would be near 80% !" >> /var/log/check_HD.log if [ $a2 -gt 89 ];then echo "$DAY $b21 would be near 80% !" >> /var/log/check_HD.log if [ $a3 -gt 89 ];then echo "$DAY $b3 would be near 80% !" >> /var/log/check_HD.log if [ $a4 -gt 89 ];then echo "$DAY $b4 would be near 80% !" >> /var/log/check_HD.log fi fi fi fi

    9、检查网站可用性

    #!/bin/bash function usage(){ echo $"usage:$0 url" exit 1 } function check_url() { wget --spider -q -o /dev/null --tries=1 -T 5 $1 if [ $? -eq 0 ] then echo "$1 is yes." exit 0 else echo "$1 is fail." exit 1 fi }

    10、用source 执行脚本和用bash 执行 Shell 脚本的区别是什么?

    bash执行脚本,在脚本执行完毕退出后,脚本定义的资源将被回收 source执行的脚本,脚本定义的资源将会加载到其父进程

    11、定义变量内容,不加引号、单引号、双引号、反引号有什么区别?

    [root@localhost test]# a=linux [root@localhost test]# echo $a linux [root@localhost test]# b="$a is" [root@localhost test]# echo $b linux is [root@localhost test]# b='$a is' [root@localhost test]# echo $b $a is [root@localhost test]# c=`date` [root@localhost test]# echo $c Mon Jul 6 15:56:32 CST 2020 不加引号:用于一些简单字符数字的定义,与双引号类似 单引号:强引,不管里面是否有变量或者其他表达都是原样子输出 双引号:如果其定义变量的时候使用双引号,则里面的变量或者函数会通过解析,解析完成后再输出,而不是把双引号中的变量名以及命令原样子输出 反引号:一般用于引用命令,执行的时候命令会被执行

    12、编写shell脚本,计算1~100的和

    sum=0 for i in {1..100} do let sum=sum+$i done echo $sum

    13、编写shell脚本,输入一个数字n并计算1~n的和

    read -p "please input a number:" n sum=0 for i in $(seq 1 $n) do let sum=$(($sum+$i)) done echo $sum

    14、编写shell脚本,批量建立用户user_00、user_01…user_99

    for i in {00..99} do useradd user_$i echo 111111 |passwd --stdin user_$i done

    15、编写shell脚本,实现两个变量之间的加减乘除运算

    read -p "please input one number:" m read -p "please input another number:" n let a=$(($m+$n)) let b=$(($m-$n)) let c=$(($m*$n)) let d=$(($m/$n)) echo "相加:$a" echo "相减:$b" echo "相乘:$c" echo "相除:$d"

    16、利用bash for循环打印下面这句话中字母数不大于6的单词

    I am clsn Welcome to my blog http://blog.znix.top

    a="I am clsn Welcome to my blog http://blog.znix.top" echo $a |awk -F "[^a-zA-Z]" '{for (i=1;i<=NF;i++){if (0<length($i) && length($i)<6){print $i}}}'

    17、请用shell或Python编写一个正(或长)方形,接收用户输入的数字

    read -p "please input the length:" b read -p "please input the width:" a for i in `seq 1 $a` do for j in `seq 1 $b` do echo -n "*" done echo "" done

    18、写一个Shell脚本解决DOS攻击生产案例

    while true do #netstat -tan |grep ESTABLISHED |awk -F "[ :]+" '{array[$6]++}END{for (i in array) print i,array[i]}' >netstat.txt netstat -tan |grep SYS_RECV |awk -F "[ :]+" '{array[$6]++}END{for (i in array) print i,array[i]}' >netstat.txt while read line do echo $line n=`echo $line |awk '{print $2}'` m=`echo $line |awk '{print $1}'` if (($n>5)) then iptables -t filter -I INPUT -s $m -j REJECT fi echo $n done < netstat.txt sleep 2 done

    19、用shell处理以下内容

    1、按单词出现频率降序排序!   2、按字母出现频率降序排序! the squid project provides a number ofresources to assist users design implement and support squid installations.Please browse the documentation and support sections for more infomation byoldboy training

    word="the squid project provides a number ofresources to assist users design implement and support squid installations.Please browse the documentation and support sections for more infomation byoldboy training" awk '{for (i=1;i<=length($0);i++){if (substr($0,i,1)~/[a-z]/) array[substr($0,i,1)]++}} END{for (i in array) print i,array[i]}' word |sort -nrk2

    20、九九乘法表

    for i in `seq 1 9` do for j in `seq 1 $i` do echo -ne "$i*$j=$(($i*$j))\t" done echo "" done
    Processed: 0.012, SQL: 9