马哥Linux培训课后作业(4)

2017-11-23|Categories: Magedu-training|

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

#!/bin/bash
myHost=`hostname`
myIP=`ifconfig ens33 | grep -w "inet" | tr -s " " | cut -d" " -f3`
myOS=`cat /etc/centos-release`
myKernel=`uname -r`
# 我设置了grep="grep -i"的alias,但脚本会禁用alias
# 所以此处grep必须添加`-i`,否则会过滤失败
myCPU=`lscpu | grep -i "model name" | tr -s " " | cut -d: -f2 | cut -c2-`
totalMem=`cat /proc/meminfo | head -n1 | tr -s " " | cut -d: -f2 | cut -c2-`
diskSize=`lsblk | grep -w "sda" | tr -s " " | cut -d" " -f4`

cat <<_EOF_
My hostname:        ${myHost}
My IP address:      ${myIP}
My OS version:      ${myOS}
My kernel version:  ${myKernel}
My CPU model:       ${myCPU}
My total memory:    ${totalMem}
My disk size:       ${diskSize}
_EOF_

编写脚本/root/bin/backup.sh,可实现每日将/etc/目录备份到/root/etcYYYY-mm-dd中

#!/bin/bash
bakDate=$(date +%F)
bakDir=/root/etc${bakDate}
mkdir ${bakDir} && cp -a /etc/* $_

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

#!/bin/bash
df | grep '/dev/sda' | tr -s " " | cut -d" " -f1,5 | sort -k2 -nr | head -n1

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

#!/bin/bash
ss -tan | tr -s " " ':' | cut -d: -f6 | grep -E "^[0-9]" | sort -nr | uniq -c | sort -nr

编写脚本/root/bin/sumid.sh,计算/etc/passwd文件中的第10个用户和第20用户的ID之和

#!/bin/bash
firstID=`head /etc/passwd | tail -n1 | cut -d: -f3`
secondID=`head -n20 /etc/passwd | tail -n1 | cut -d: -f3`

sum=$(( ${firstID} + ${secondID} ))
echo ${sum}

编写脚本/root/bin/sumspace.sh,传递两个文件路径作为参数给脚本,计算这两个文件中所有空白行之和

#!/bin/bash
blankLinesOfFile1=`grep -cE "^$" $1`
blankLinesOfFile2=`grep -cE "^$" $2`

sum=$(( ${blankLinesOfFile1} + ${blankLinesOfFile2} ))
echo "There are ${sum} blank lines in $1 and $2."

编写脚本/root/bin/sumfile.sh,统计/etc, /var, /usr目录共有多少个一级子目录和文件

#!/bin/bash
path1="/etc/"
path2="/var/"
path3="/usr/"

path1L1Dirs=`ls -ap ${path1} | grep -cE "/$"`
path2L1Dirs=`ls -ap ${path2} | grep -cE "/$"`
path3L1Dirs=`ls -ap ${path3} | grep -cE "/$"`

path1L1Files=`ls -ap ${path1} | grep -cvE "/$"`
path2L1Files=`ls -ap ${path2} | grep -cvE "/$"`
path3L1Files=`ls -ap ${path3} | grep -cvE "/$"`

sumL1Dirs=$(( ${path1L1Dirs} + ${path2L1Dirs} + ${path3L1Dirs} ))
sumL1Files=$(( ${path1L1Files} + ${path2L1Files} + ${path3L1Files} ))

echo "There are ${sumL1Dirs} level 1 directories in ${path1}, ${path2}, ${path3}."
echo "There are ${sumL1Files} level 1 files in ${path1}, ${path2}, ${path3}."

Leave A Comment