linux-shell 练习题
1、编写脚本 systeminfo.sh,显示当前主机系统信息,包括主机名,IPv4地址,操作系统版本,内核版本,CPU型号,内存大小,硬盘大小
[root@CentOS7 scripts]# cat systeminfo.sh
#!/bin/bash
#
COLOR="\033[1;31m"
COLOR_END="\033[0m"
ECHO="echo -e"
$ECHO "hostname is ${COLOR}`hostname`$COLOR_END"
$ECHO "ipaddr is ${COLOR}`ifconfig ens33|grep -Eo '(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])'|head -1`$COLOR_END"
$ECHO "os info is ${COLOR}`cat /etc/redhat-release`$COLOR_END"
$ECHO "kenel info is ${COLOR}`uname -r`$COLOR_END"
$ECHO "cpuinfo is ${COLOR}`lscpu|grep 'Model name:'|tr -s ' '|cut -d: -f2|sed -r 's/^[[:space:]]//'`$COLOR_END"
$ECHO "Meminfo is ${COLOR}`free -h|grep 'Mem'|tr -s ' ' ':'|cut -d':' -f2`$COLOR_END"
$ECHO "disk space is ${COLOR}`lsblk|grep 'disk'|tr -s ' '|cut -d' ' -f4`$COLOR_END"
2、编写脚本 backup.sh,可实现每日将/etc/目录备份到/backup/etcYYYY-mm-dd中
[root@CentOS7 scripts]# cat backup.sh
#!/bin/bash
#
DIR=/backup/etc`date +"%F-%T"`
if [ ! -d "$DIR" ];then
mkdir -p $DIR
fi
echo -e "\033[1;31mstart backup /etc directory\033[0m"
cp -rv --preserve=mode /etc $DIR
echo -e "\033[1;31m/etc directory backup at $DIR\033[0m\a"
3、编写脚本 disk.sh,显示当前硬盘分区中空间利用率最大的值
[root@CentOS7 scripts]# cat disk.sh
#!/bin/bash
#
diskSpace=`df -h|grep "/dev/sd"|tr -s ' '|cut -d' ' -f5|tr -d '%'|sort -nr|head -1`
echo -e "\033[1;31mdisk space max is ${diskSpace}%\033[0m"
4、编写脚本 links.sh,显示正连接本主机的每个远程主机的IPv4地址和连接数,并按连接数从大到小排序
[root@CentOS7 scripts]# cat links.sh
#!/bin/bash
#
foreign_ip_connect=`netstat -nt|tr -s ' ' ':'|cut -d: -f6|grep -Eo '(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])'|sort|uniq -c|sort -nr`
echo -e "\033[1;31m$foreign_ip_connect\033[0m"