SHELL脚本编程练习答案(多版本)

练习:
1、编写脚本 systeminfo.sh,显示当前主机系统信息,包括:主机名,IPv4地址,操作系统版本,内核
版本,CPU型号,内存大小,硬盘大小

#!/bin/bash
YELLOW='\e[1;33m'
RED='\e[1;31m'
END='\e[0m'

echo -e "${YELLOW}++++++++++++++++++++++++++++++++++++++++++${END}"
echo -e "${RED}HOSTNAME:        `hostname`${END}"
echo -e "${RED}IPADDR:          `hostname -I`${END}"
echo -e "${RED}OS's version:    `cat /etc/centos-release`${END}"
echo -e "${RED}Kernel version:  `uname -r`${END}"
echo -e "${RED}CPU:            `lscpu |egrep '^Model name'|tr -s ' '|cut -d: -f2`${END}"
echo -e "${RED}Memory size:     `free -h|sed -rn '2p'|tr -s ' '|cut -d' ' -f2`${END}"
echo -e "${RED}Disk size:       `lsblk |sed -n '2p'|egrep -o '([0-9]+)G'`${END}"
echo -e "${YELLOW}++++++++++++++++++++++++++++++++++++++++++${END}"

2、编写脚本 backup.sh,可实现每日将 /etc/ 目录备份到 /backup/etcYYYY-mm-dd中
版本1:

#!/bin/bash
RED='\e[1;31m'
GREEN='\e[1;32m'
END='\e[0m'
SOURCE="/etc"
DEST="/backup"

[ ! -d $DEST ] && { mkdir $DEST;echo -e "${RED}Start backup...${END}";sleep 3;cp -av $SOURCE $DEST/etc`date +%F`;echo -e "${GREEN}Back is finished.${END}"; } || { echo -e "${RED}Start backup...${END}";sleep 3;cp -av $SOURCE $DEST/etc`date +%F`;echo -e "${GREEN}Back is finished.${END}"; }

版本2:

#!/bin/bash
RED='\e[1;31m'
GREEN='\e[1;32m'
END='\e[0m'
SOURCE="/etc"
DEST="/backup"

if [ ! -d $DEST ];then
  mkdir $DEST
  echo -e "${RED}Start backup...${END}"
  sleep 3
  cp -av $SOURCE $DEST/etc`date +%F`
  echo -e "${GREEN}Back is finished.${END}"
else
  echo -e "${RED}Start backup...${END}"
  sleep 3
  cp -av $SOURCE $DEST/etc`date +%F`
  echo -e "${GREEN}Back is finished.${END}"
fi

3、编写脚本 disk.sh,显示当前硬盘分区中空间利用率最大的值

#!/bin/bash
COLOR='\e[1;36m'
END='\e[0m'
MAX=`df|egrep '^/dev/sd'|egrep -o '([0-9]+)%' |tr -d '%'|sort -nr|head -1`

echo -e "${COLOR}The maximum value of space is $MAX in the hard disk partition.${END}"

4、编写脚本 links.sh,显示正连接本主机的每个远程主机的IPv4地址和连接数,并按连接数从大到小排

#!/bin/bash
COLOR='\e[1;34m'
END='\e[0m'
RESULT=`netstat -tan|egrep 'ESTABLISHED'|tr -s ' ' :|cut -d: -f6|sort|uniq -c|sort -nr`

echo -e "${COLOR}Active Internet connections's status:\n${RESULT}${END}"

1、编写脚本 argsnum.sh,接受一个文件路径作为参数;如果参数个数小于1,则提示用户“至少应该给
一个参数”,并立即退出;如果参数个数不小于1,则显示第一个参数所指向的文件中的空白行数
版本1:

#!/bin/bash
[ $# -lt 1 ] && { echo -e "\e[1;31mPlease at least give an argument.\e[0m";exit 2; } 
[ $# -ge 1 ] && echo -e "\e[1;35mBlank lines is `grep '^$' $1 $2 $3|wc -l`.\e[0m"

版本2:

#!/bin/bash
if [ $# -lt 1 ];then
  echo -e "\e[1;31mPlease at least input a filename as an argument.\e[0m"
  exit 2
else
  echo -e "\e[1;36mBlank line is `egrep '^$' $1 $2 $3 | wc -l`.\e[0m"
fi  

2、编写脚本 hostping.sh,接受一个主机的IPv4地址做为参数,测试是否可连通。如果能ping通,则提
示用户“该IP地址可访问”;如果不可ping通,则提示用户“该IP地址不可访问”
版本1:

#!/bin/bash
IP=10.0.0.7
RED='\e[1;31m'
GREEN='\e[1;32m'
ping -c1 -W1 $IP &> /dev/null && echo -e "${GREEN}${IP} is up.${END}" || echo -e "${RED}${IP} is down.${END}"

版本2:

#!/bin/bash
RED='\e[1;31m'
GREEN='\e[1;32m'
END='\e[0m'
IP=10.0.0.2
if ping -c1 -W1 $IP &> /dev/null;then
  echo -e "${GREEN}${IP} is up.${END}"
else
  echo -e "${RED}${IP} is down.${END}"
fi  

版本3:

#!/bin/bash
IP=10.0.0
RED='\e[1;31m'
GREEN='\e[1;32m'
END='\e[0m'

for i in `seq 254`;do
  ping -c1 -W1 ${IP}.${i} &> /dev/null && echo -e "${GREEN}${IP}.${i} is up.${END}" || echo -e "${RED}${IP}.${i} is down.${END}"
done

3、编写脚本 checkdisk.sh,检查磁盘分区空间和inode使用率,如果超过80%,就发广播警告空间将

版本1:

#!/bin/bash
WARN=20
GREEN='\e[1;32m'
END='\e[0m'
SPACE_USED=`df|egrep '^/dev/sd'|egrep -o '([0-9]+)%' |tr -d '%'|sort -nr|head -1`
INODE_USED=`df -i|egrep '^/dev/sd'|egrep -o '([0-9]+)%' |tr -d '%'|sort -nr|head -1`

[ $SPACE_USED -ge $WARN -o $INODE_USED -ge $WARN ] && echo "space will be full." | mail -s diskwarning [email protected] || echo -e "${GREEN}Disk space is enough.${END}"

版本2:

#!/bin/bash
WARN=20
YELLOW='\e[1;33m'
END='\e[0m'
DISK_USED=`df|egrep '/dev/sd'|egrep -o '([0-9]+)%'|tr -d '%'|sort -nr|head -1`
INODE_USED=`df -i|egrep '^/dev/sd'|egrep -o '([0-9]+)%' |tr -d '%'|sort -nr|head -1`

if [ $DISK_USED -ge $WARN -o $INODE_USED -ge $WARN ];then
  echo "Disk space will be full." |mail -s Diskwarning [email protected]
else
  echo -e "${YELLOW}Disk space is enough.${END}"
fi 

版本3:

#!/bin/bash
WARN=10
RED='\e[1;31m'
BLUE='\e[1;34m'
END='\e[0m'

DISK_USED=`df|egrep '^/dev/sd'|egrep -o '([0-9]+)%' |tr -d '%'`

for i in $DISK_USED;do
  [ $i -ge $WARN ] && echo -e "${RED}Disk space will be full.${END}" || echo -e "${BLUE}Disk space is enough.${END}"
done

4、编写脚本 per.sh,判断当前用户对指定参数文件,是否不可读并且不可写
版本1:

#!/bin/bash
read -p "Please input a filename: " FILE
[ ! -r $FILE -a ! -w $FILE ] && echo "$FILE is not readable and not writeable" || echo "$FILE is readable or writeable."

版本2:

#!/bin/bash
COLOR1='\e[1;33m'
COLOR2='\e[1;34m'
END='\e[0m'
if [ $# -ne 0 ];then
  [ ! -r $1 -a ! -w $1 ] && echo -e "${COLOR1}$1 is not readable and not writeable.${END}" || echo -e "${COLOR2}$1 is readable or writeable.${END}"
else
  echo -e "${COLOR1}Please input a file.${END}"
fi

5、编写脚本 excute.sh ,判断参数文件是否为sh后缀的普通文件,如果是,添加所有人可执行权限,
否则提示用户非脚本文件
版本1:

#!/bin/bash
RED='\e[1;31m'
YELLOW='\e[1;33m'
END='\e[0m'
read -p "Please input a filename: " FILE
[[ "$FILE" =~ ^.*\.sh$ ]] && { chmod a+x $FILE;echo -e "${YELLOW}${FILE}'s executeable is added.${END}"; }  || echo -e "${RED}${FILE} is not a script file.${END}"

版本2:

#!/bin/bash
RED='\e[1;31m'
YELLOW='\e[1;33m'
END='\e[0m'
read -p "Please input a filename: " FILE
if [[ "$FILE" =~ ^.*\.sh$ ]];then
  chmod a+x $FILE
  echo -e "${YELLOW}${FILE}'s executeable permission is added.${END}"
else
  echo -e "${RED}${FILE} is not a script file.${END}"
fi 

6、编写脚本 nologin.sh和 login.sh,实现禁止和允许普通用户登录系统
版本1:

#!/bin/bash
YELLOW='\e[1;33m'
END='\e[0m'
FILE="/etc/nologin"

[ ! -e $FILE ] && { touch $FILE; echo -e "${YELLOW}Prohibit common user login.${END}"; } || echo -e "${YELLOW}Cmmon user can not login.${END}"

版本2:

#!/bin/bash
YELLOW='\e[1;33m'
RED='\e[1;31m'
END='\e[0m'
FILE="/etc/nologin"

if [ ! -e $FILE ];then
  touch $FILE 
  echo -e "${YELLOW}Prohibit common user login.${END}"
else  
  echo -e "${RED}Cmmon user can not login.${END}"
fi

练习
1、让所有用户的PATH环境变量的值多出一个路径,例如:/usr/local/apache/bin

echo "export PATH=/usr/local/apache/bin:$PATH" >> /etc/profile
source /etc/profile
echo $PATH

2、用户 root 登录时,将命令指示符变成红色,并自动启用如下别名: rm=‘rm -i’
cdnet=‘cd /etc/sysconfig/network-scripts/’
editnet=‘vim /etc/sysconfig/network-scripts/ifcfg-eth0’
editnet=‘vim /etc/sysconfig/network-scripts/ifcfg-eno16777736 或 ifcfg-ens33 ’ (如果系统是
CentOS7)

echo PS1="\[\e[1;32m\][\[\e[0m\]\[\e[1;32m\]\u\[\e[32m\]@\h\[\e[1;32m\] \W\[\e[1;32m\]]\[\e[0m\]\\$ " >> /etc/profile.d/env.sh
cat <<EOF >> ~/.bashrc
>rm='rm -i'
>cdnet='cd /etc/sysconfig/network-scripts/'
>editnet='vim /etc/sysconfig/network-scripts/ifcfg-eth0'
>EOF

3、任意用户登录系统时,显示红色字体的警示提醒信息“Hi,dangerous!”

echo -e "\e[1;31mHi,dangerous!\e[0m" >> /etc/motd

4、编写生成脚本基本格式的脚本,包括作者,联系方式,版本,时间,描述等

vim ~/.vimrc
set ts=2
set expandtab
set ignorecase
set autoindent
autocmd BufNewFile *.sh exec ":.call SetTitle()"
func SetTitle()
if expand("%:e") == 'sh'
    call setline(1,"#!/bin/bash")
    call setline(2,"#***********************************************")
    call setline(3,"#Author:         Kingdom_xu")
    call setline(4,"#Mail:           [email protected]")
    call setline(5,"#Version:        1.0")
    call setline(6,"#Date:           ".strftime("%Y-%m-%d"))
    call setline(7,"#FileName:       ".expand("%"))
    call setline(8,"#Description:    The test script")
    call setline(9,"#Copyright (C):  ".strftime("%Y")." All rights reserved")
    call setline(10,"#***********************************************")
    call setline(11,"")
endif
endfunc
autocmd BufNewFile * normal G

练习
1、编写脚本 createuser.sh,实现如下功能:使用一个用户名做为参数,如果指定参数的用户存在,就
显示其存在,否则添加之。并设置初始密码为123456,显示添加的用户的id号等信息,在此新用户第一
次登录时,会提示用户立即改密码,如果没有参数,就提示:请输入用户名
版本1:

#!/bin/bash
read -p "Please input a username: " NAME

[ -z $NAME ] && { echo -e "\e[1;33mPlease give a username.\e[0m";exit 2; }
id $NAME &> /dev/null && { echo -e "\e[1;36m$NAME is exist.\e[0m"; } || { useradd $NAME;echo $NAME:123456 | chpasswd $NAME;getent passwd $NAME;passwd -e $NAME &> /dev/null; }

版本2:

#!/bin/bash
read -p "Please input a username: " NAME

if [ -z $NAME ];then
  echo -e "\e[1;37mInput a username.\e[0m"
  exit 2
fi

if getent passwd $NAME;then
  echo -e "\e[1;32m$NAME is exist.\e[0m"
else
  useradd $NAME
  echo $NAME:123456 | chpasswd $NAME
  id $NAME 
  passwd -e $NAME &> /dev/null
fi

2、编写脚本 yesorno.sh,提示用户输入yes或no,并判断用户输入的是yes还是no,或是其它信息

#!/bin/bash
read -p "Please input yes or no: " ANS

case $ANS in
[Yy]|[Yy][Ee][Ss])
  echo -e "\e[1;34mYour answer is YES.\e[0m"
  ;;
[Nn]|[Nn][Oo])
  echo -e "\e[1;35mYour answer is NO.\e[0m"
  ;;
*)
  echo -e "\e[1;33mPlease input yse or no.\e[0m"
esac

3、编写脚本 filetype.sh,判断用户输入文件路径,显示其文件类型(普通,目录,链接,其它文件类
型)

#!/bin/bash
read -p "Input a filename: " FILE
TYPE=`ls -ld $FILE|egrep -o '^.'`

case $TYPE in
-)
  echo -e "\e[1;31m$FILE is a normal file.\e[0m"
  ;;
d)
  echo -e "\e[1;32m$FILE is a directory file.\e[0m"
  ;;
l)
  echo -e "\e[1;33m$FILE is a link file.\e[0m"
  ;;
b)  
  echo -e "\e[1;34m$FILE is a block file.\e[0m"
  ;;
c)  
  echo -e "\e[1;35m$FILE is a character file.\e[0m"
  ;;
s)
  echo -e "\e[1;36m$FILE is a socket file.\e[0m"
  ;;
p)
  echo -e "\e[1;37m$FILE is a pipe file.\e[0m"
  ;;
*)
  echo -e "\e[1;31m$FILE is other type file.\e[0m"
esac

4、编写脚本 checkint.sh,判断用户输入的参数是否为正整数

#!/bin/bash
read -p "Please input a digit: " NUM

[[ "$NUM" =~ ^[0-9]+$ ]] && echo -e "\e[1;32m$NUM is a positive integer.\e[0m" || echo -e "\e[1;31m$NUM is not a positive integer.\e[0m"

5、编写脚本 reset.sh,实现系统安装后的初始化环境,包括:1、别名 2、环境变量,如PS1等 3、
安装常用软件包,如:tree 5、实现固定的IP的设置,6、vim的设置等

#!/bin/bash
echo -e "\e[1;31mThis is a system initialization script.\e[0m"
echo -e "\e[1;$[RANDOM%7+31]m"
cat <<EOF
1)禁用SElinux、防火墙
2)安装常用软件包
3)更改yum源
4)修改网卡名和静态地址
5)别名
6)vim设置
7)输入错误,重新选择
EOF
echo -e "\e[0m"

read -p "Please choose a option from menu(1-6): " MENU
case $MENU in
1)
  echo -e "\e[1;31mStarting turn off SElinux and Firewalld.\e[0m"
  egrep '^SELINUX=' /etc/selinux/config |sed -i 's/enforcing/disabled/' &> /dev/null
  setenforce 0 &> /dev/null
  systemctl stop firewall &> /dev/null
  systemctl disable --now firewall &> /dev/null
  echo -e "\e[1;31mTurned off SElinux and firewalld finished.\e[0m"
  ;;
2)
  echo -e "\e[1;32mStarting install many packages.\e[0m"
  yum -y install wget vim net-tools
  yum -y install psmisc tree bc
  echo -e "\e[1;32mInstall packages finished.\e[0m"
  ;;
3)
  echo -e "\e[1;33mStarting update yum resource.\e[0m"
  wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-8.repio &> /dev/null
  yum makecache &> /dev/null
  echo -e "\e[1;33mUpdate yum resource finished.\e[0m"
  ;;
4)
  DIR="/etc/sysconfig/network-scripts"
  echo -e "\e[1;34mStarting modify network configure.\e[0m"
  nmcli connection add type ethernet con-name eth0 ifname ens160 &> /dev/null
  nmcli connection delete ens160 &> /dev/null
  sed -i 's/ens160/eth0/g' $DIR/ifcfg-eth0  &> /dev/null
  sed -i 's/dhcp/static/' $DIR/ifcfg-eth0 &> /dev/null 
  sed -i '/^GRUB_CMDLINE_LINUX=/s/"$/ net.ifnames=0"/' /etc/default/grub &> /dev/null
  grub2-mkconfig -o /boot/grub2/grub.cfg &> /dev/null
  echo  "IPADDR=10.0.0.8\nPREFIX=24\nGATEWAY=10.0.0.2" >> $DIR/ifcfg-eth0
  echo -e "\e[1;34mModified network configure finished.\e[0m"
  ;;
5)
  echo -e "\e[1;35mStarting define alias name.\e[0m"
  alias rm='cp -a /etc /data'
  alias cdnet='cd /etc/sysconfig/network-scripts'
  alias editnet='vim /etc/sysconfig/network-scripts/ifcfg-eth0'
  echo -e "\e[1;35mDefined alias name finished.\e[0m"
  ;;
6)
  echo -e "\e[1;36mStarting configure ~/.vimrc file.\e[0m"
  cat /data/vimrc.txt > ~/.vimrc 
    echo -e "\e[1;37mConfigure ~/.vimrc finished.\e[0m"
    ;;
*)
    echo -e "\e[1;31mInvalid option,please choose again.\e[0m"
  ;;
esac

猜你喜欢

转载自blog.51cto.com/14880320/2518301