轉載實驗樓課程
一、實驗介紹
1.1 實驗內容
本課程實現 shell 腳本監控系統的各項參數,並可以將腳本加入系統環境中,可以直接在終端裏執行。還添加了幾個參數,一個腳本可以執行不同的操作。
1.2 知識點
本實驗涵蓋以下知識點:
- Bash 腳本編程
- 如何獲取 Linux 系統信息
- 如何實時獲取 Linux 資源使用率
1.3 實驗環節
- vim編輯器
- shell解釋器(linux自帶)
1.4 適合人羣
適合人羣:本課程適合有shell語法基礎,想學習shell腳本的實際使用的同學,可以加深對於shell腳本的認識
1.5 代碼獲取
#獲取
http://labfile.oss.aliyuncs.com/courses/597/monitor.sh
#運行
bash monitor.sh
#備註
如果執行monitor -i安裝提示輸入密碼。可以執行passwd root爲root設置密碼
如果安裝之後不能運行,修改/usr/bin/monitor.sh的權限
1.6 效果截圖
在實驗中,我們將逐步實現下面的功能需求:
- 通過腳本查看系統的使用情況,實現對linux的系統監控。
- 將寫好的腳本加入系統環境,開啓終端即可使用
- 給腳本添加參數,可以實現不同的操作。
最終實現的腳本運行效果:
二、實驗原理
2.1 主要命令介紹
- 查看內存(
free
) - 查看磁盤(
df
) - 查看cpu佔用率(
top
) - 查看內核版本(
uname
)
這些命令是linux管理員必須耳熟能詳的基本命令,本課程的監控腳本,也是根據這些命令的返回值做處理,然後打印在終端的,同學們可以敲一敲這些命令,看看他們的基本用法。
命令詳解請查看
http://man.linuxde.net/
2.2 shell編程注意
``
用法 這個符號可以保存命令的返回值,如
PATH=`pwd` #也可以寫成 PAHT=$(pwd)
echo $PATH
#輸出pwd命令的值,也就是當前路徑
- 參數說明
$1
表示第一個參數,$2
表示第二個參數,$#
表示參數個數
如果讀者對於這些不熟悉,要先學習高級Bash腳本編程指南,其中shell的基本語法
三、實驗步驟
打開終端,進入Code
目錄,創建文件tecmint_monitor.sh
。
getopts
:可以獲取用戶在命令下的參數,然後根據不同的參數進行不同的操作。它的使用方法是getopts option_string
variable,option_string 是指字符串,會逐個匹配,variable 每次匹配成功的選項。
#! /bin/bash
while getopts ivh name # getopts 有三個參數,分別執行安裝,查看版本,幫助說明
do
case $name in
i)iopt=1;;
v)vopt=1;;
h)hopt=1;;
*)echo "Invalid arg";;
esac
done
這個腳本主要有 -ivh
三個參數,分別執行安裝腳本,查看版本,幫助說明,你也可以添加自己想要的參數。如果不加參數,默認執行系統的監控命令並打印到屏幕上。
3.1 有關參數 i
的模塊
這個部分主要是將腳本添加到環境的目錄裏,通過終端就可以執行命令。
if [[ ! -z $iopt ]] #如果iopt非空則執行
then
{
wd=$(pwd)
basename "$(test -L "$0" && readlink "$0" || echo "$0")" > /tmp/scriptname
#basename命令會刪掉所有的前綴包括最後一個slash(‘/’)字符,然後將字符串顯示出來
scriptname=$(echo -e -n $wd/ && cat /tmp/scriptname)
#scriptname就是tecmint_monitor.sh的地址
su -c "cp $scriptname /usr/bin/monitor" root && echo "Congratulations! Script Installed, now run monitor Command" || echo "Installation failed"
}
fi
3.2 有關參數 v
的模塊
這個部分是查看腳本的版本,版權等信息。
if [[ ! -z $vopt ]]
then
{
echo -e "tecmint_monitor version 0.1\nReleased Under Apache 2.0 License"
}
fi
3.3 有關參數 h
的模塊
這個部分是添加幫助信息,方便其他人使用
if [[ ! -z $hopt ]]
then
{
echo -e " -i Install script"
echo -e " -v Print version information and exit"
echo -e " -h Print help (this information) and exit"
}
fi
3.4提取信息設置變量
先設置一些好記的變量名,這樣方便閱讀,比直接看代碼要更容易一點。
clear
unset tecreset os architecture kernelrelease internalip externalip nameserver loadaverage
# unset命令用於刪除已定義的shell變量(包括環境變量)和shell函數。
# 關於unset更多的信息可以查看http://www.runoob.com/linux/linux-comm-unset.html
# 定義變量 tecreset
tecreset=$(tput sgr0)
# 查看是否可以連網
ping -c 1 www.baidu.com &> /dev/null && echo -e '\E[32m'"Internet: $tecreset Connected" || echo -e '\E[32m'"Internet: $tecreset Disconnected"
# '\E[32m' 將打印的信息設置爲綠色
# 查看系統的類型
os=$(uname -o)
echo -e '\E[32m'"Operating System Type :" $tecreset $os
# 查看系統的版本和名稱
###################################
OS=`uname -s`
REV=`uname -r`
MACH=`uname -m`
GetVersionFromFile()
{
VERSION=`cat $1 | tr "\n" ' ' | sed s/.*VERSION.*=\ // `
}
查看操作系統的類型,不同的操作系統指令是不一樣的。看到大段的代碼不要緊張,其實邏輯很簡單。
if [ "${OS}" = "SunOS" ] ; then
OS=Solaris
ARCH=`uname -p`
OSSTR="${OS} ${REV}(${ARCH} `uname -v`)"
# uname命令用於打印當前系統相關信息(內核版本號、硬件架構、主機名稱和操作系統類型等)。
elif [ "${OS}" = "AIX" ] ; then
OSSTR="${OS} `oslevel` (`oslevel -r`)"
#AIX是IBM開發的一套類UNIX操作系統,關於它更多的指令可以查看http://www.cnblogs.com/sbaicl/articles/2947795.html
elif [ "${OS}" = "Linux" ] ; then
KERNEL=`uname -r`
if [ -f /etc/redhat-release ] ; then
DIST='RedHat'
PSUEDONAME=`cat /etc/redhat-release | sed s/.*\(// | sed s/\)//`
REV=`cat /etc/redhat-release | sed s/.*release\ // | sed s/\ .*//`
#sed通常用來匹配一個或多個正則表達式的文本進行處理,可以查看http://coolshell.cn/articles/9104.html
elif [ -f /etc/SuSE-release ] ; then
DIST=`cat /etc/SuSE-release | tr "\n" ' '| sed s/VERSION.*//`
REV=`cat /etc/SuSE-release | tr "\n" ' ' | sed s/.*=\ //`
elif [ -f /etc/mandrake-release ] ; then
DIST='Mandrake'
PSUEDONAME=`cat /etc/mandrake-release | sed s/.*\(// | sed s/\)//`
REV=`cat /etc/mandrake-release | sed s/.*release\ // | sed s/\ .*//`
elif [ -f /etc/debian_version ] ; then
DIST="Debian `cat /etc/debian_version`"
REV=""
fi
if ${OSSTR} [ -f /etc/UnitedLinux-release ] ; then
DIST="${DIST}[`cat /etc/UnitedLinux-release | tr "\n" ' ' | sed s/VERSION.*//`]"
fi
OSSTR="${OS} ${DIST} ${REV}(${PSUEDONAME} ${KERNEL} ${MACH})"
fi
最後就是監控系統的各種信息,並打印到屏幕
查看操作系統版本
echo -e '\E[32m'"OS Version :" $tecreset $OSSTR
# 查看系統的類型
architecture=$(uname -m)
echo -e '\E[32m'"Architecture :" $tecreset $architecture
# 查看內核的版本
kernelrelease=$(uname -r)
echo -e '\E[32m'"Kernel Release :" $tecreset $kernelrelease
# 查看主機名
echo -e '\E[32m'"Hostname :" $tecreset $HOSTNAME
# 查看內網地址
internalip=$(hostname -I)
echo -e '\E[32m'"Internal IP :" $tecreset $internalip
# 查看外網地址
externalip=$(curl -s ipecho.net/plain;echo)
echo -e '\E[32m'"External IP : $tecreset "$externalip
# 查看DNS
nameservers=$(cat /etc/resolv.conf | sed '1 d' | awk '{print $2}')
echo -e '\E[32m'"Name Servers :" $tecreset $nameservers
# 查看登陸的用戶
who>/tmp/who
echo -e '\E[32m'"Logged In users :" $tecreset && cat /tmp/who
# 查看系統內存使用情況
free -h | grep -v + > /tmp/ramcache
echo -e '\E[32m'"Ram Usages :" $tecreset
cat /tmp/ramcache | grep -v "Swap"
echo -e '\E[32m'"Swap Usages :" $tecreset
cat /tmp/ramcache | grep -v "Mem"
# 查看磁盤使用情況
df -h| grep 'Filesystem\|/dev/sda*' > /tmp/diskusage
echo -e '\E[32m'"Disk Usages :" $tecreset
cat /tmp/diskusage
# 查看系統的負載情況
loadaverage=$(top -n 1 -b | grep "load average:" | awk '{print $10 $11 $12}')
echo -e '\E[32m'"Load Average :" $tecreset $loadaverage
# 查看系統的運行時間
tecuptime=$(uptime | awk '{print $3,$4}' | cut -f1 -d,)
echo -e '\E[32m'"System Uptime Days/(HH:MM) :" $tecreset $tecuptime
# 刪除上面使用的變量,釋放資源
unset tecreset os architecture kernelrelease internalip externalip nameserver loadaverage
# 刪除臨時文件
rm /tmp/who /tmp/ramcache /tmp/diskusage
}
fi
四、實驗總結
通過這個小項目,加強了對shell編程的理解,不僅可以執行腳本,還可以將腳本安裝到系統環境中,直接執行命令。從實踐中學習,把代碼敲一遍,就能體會編程的樂趣了:-)
最後附上源代碼
#! /bin/bash
# unset any variable which system may be using
# clear the screen
while getopts ivh name
do
case $name in
i)iopt=1;;
v)vopt=1;;
h)hopt=1;;
*)echo "Invalid arg";;
esac
done
#
if [[ ! -z $iopt ]]
then
{
wd=$(pwd)
basename "$(test -L "$0" && readlink "$0" || echo "$0")" > /tmp/scriptname
scriptname=$(echo -e -n $wd/ && cat /tmp/scriptname)
su -c "cp $scriptname /usr/bin/monitor" root && echo "Congratulations! Script Installed, now run monitor Command" || echo "Installation failed"
}
fi
if [[ ! -z $vopt ]]
then
{
echo -e "tecmint_monitor version 0.1\nDesigned by Tecmint.com\nReleased Under Apache 2.0 License"
}
fi
if [[ ! -z $hopt ]]
then
{
echo -e " -i Install script"
echo -e " -v Print version information and exit"
echo -e " -h Print help (this information) and exit"
}
fi
if [[ $# -eq 0 ]]
then
{
clear
unset tecreset os architecture kernelrelease internalip externalip nameserver loadaverage
# Define Variable tecreset
tecreset=$(tput sgr0)
# Check if connected to Internet or not
ping -c 1 www.baidu.com &> /dev/null && echo -e '\E[32m'"Internet: $tecreset Connected" || echo -e '\E[32m'"Internet: $tecreset Disconnected"
# Check OS Type
os=$(uname -o)
echo -e '\E[32m'"Operating System Type :" $tecreset $os
# Check OS Release Version and Name
###################################
OS=`uname -s`
REV=`uname -r`
MACH=`uname -m`
GetVersionFromFile()
{
VERSION=`cat $1 | tr "\n" ' ' | sed s/.*VERSION.*=\ // `
}
if [ "${OS}" = "SunOS" ] ; then
OS=Solaris
ARCH=`uname -p`
OSSTR="${OS} ${REV}(${ARCH} `uname -v`)"
elif [ "${OS}" = "AIX" ] ; then
OSSTR="${OS} `oslevel` (`oslevel -r`)"
elif [ "${OS}" = "Linux" ] ; then
KERNEL=`uname -r`
if [ -f /etc/redhat-release ] ; then
DIST='RedHat'
PSUEDONAME=`cat /etc/redhat-release | sed s/.*\(// | sed s/\)//`
REV=`cat /etc/redhat-release | sed s/.*release\ // | sed s/\ .*//`
elif [ -f /etc/SuSE-release ] ; then
DIST=`cat /etc/SuSE-release | tr "\n" ' '| sed s/VERSION.*//`
REV=`cat /etc/SuSE-release | tr "\n" ' ' | sed s/.*=\ //`
elif [ -f /etc/mandrake-release ] ; then
DIST='Mandrake'
PSUEDONAME=`cat /etc/mandrake-release | sed s/.*\(// | sed s/\)//`
REV=`cat /etc/mandrake-release | sed s/.*release\ // | sed s/\ .*//`
elif [ -f /etc/debian_version ] ; then
DIST="Debian `cat /etc/debian_version`"
REV=""
fi
if ${OSSTR} [ -f /etc/UnitedLinux-release ] ; then
DIST="${DIST}[`cat /etc/UnitedLinux-release | tr "\n" ' ' | sed s/VERSION.*//`]"
fi
OSSTR="${OS} ${DIST} ${REV}(${PSUEDONAME} ${KERNEL} ${MACH})"
fi
##################################
#cat /etc/os-release | grep 'NAME\|VERSION' | grep -v 'VERSION_ID' | grep -v 'PRETTY_NAME' > /tmp/osrelease
#echo -n -e '\E[32m'"OS Name :" $tecreset && cat /tmp/osrelease | grep -v "VERSION" | grep -v CPE_NAME | cut -f2 -d\"
#echo -n -e '\E[32m'"OS Version :" $tecreset && cat /tmp/osrelease | grep -v "NAME" | grep -v CT_VERSION | cut -f2 -d\"
echo -e '\E[32m'"OS Version :" $tecreset $OSSTR
architecture=$(uname -m)
echo -e '\E[32m'"Architecture :" $tecreset $architecture
kernelrelease=$(uname -r)
echo -e '\E[32m'"Kernel Release :" $tecreset $kernelrelease
echo -e '\E[32m'"Hostname :" $tecreset $HOSTNAME
internalip=$(hostname -I)
echo -e '\E[32m'"Internal IP :" $tecreset $internalip
externalip=$(curl -s ipecho.net/plain;echo)
echo -e '\E[32m'"External IP : $tecreset "$externalip
nameservers=$(cat /etc/resolv.conf | sed '1 d' | awk '{print $2}')
echo -e '\E[32m'"Name Servers :" $tecreset $nameservers
who>/tmp/who
echo -e '\E[32m'"Logged In users :" $tecreset && cat /tmp/who
free -h | grep -v + > /tmp/ramcache
echo -e '\E[32m'"Ram Usages :" $tecreset
cat /tmp/ramcache | grep -v "Swap"
echo -e '\E[32m'"Swap Usages :" $tecreset
cat /tmp/ramcache | grep -v "Mem"
df -h| grep 'Filesystem\|/dev/sda*' > /tmp/diskusage
echo -e '\E[32m'"Disk Usages :" $tecreset
cat /tmp/diskusage
loadaverage=$(top -n 1 -b | grep "load average:" | awk '{print $10 $11 $12}')
echo -e '\E[32m'"Load Average :" $tecreset $loadaverage
tecuptime=$(uptime | awk '{print $3,$4}' | cut -f1 -d,)
echo -e '\E[32m'"System Uptime Days/(HH:MM) :" $tecreset $tecuptime
unset tecreset os architecture kernelrelease internalip externalip nameserver loadaverage
rm /tmp/who /tmp/ramcache /tmp/diskusage
}
fi
shift $(($OPTIND -1))
# shift命令用於對參數的移動(左移)。可以查看http://blog.csdn.net/zhu_xun/article/details/24796235
#