本脚本用到的主要命令有dialog和chkconfig,系统中必需有安装这两个命令才能运行本脚本。以下是脚本内容:
#!/bin/bash
##功能: 图形化显示开启和关闭服务
##作者: huangyandong
##博客: http://huangyandong.blog.51cto.com/
#获取系统中启用和关闭的服务列表转换为dialog --checklist需要的数据格式
function getService()
{
#注:若系统为英文则将"启用"换成"ON"
chkconfig --list|gawk '{split($5,mode,":"); if (mode[2] == "启用") print $1,$1,"ON";else print $1,$1,"OFF" ;}'|tr '\n' " "
}
#服务的开启和关闭(3和5下权限)
function serviceOn()
thisService="$1";
state="${2:-on}";
if [ -n "$thisService" ];then
chkconfig --level 35 "$thisService" $state
fi
#管理服务
function manageService()
startList="$1";
#所有服务列表
declare -a serviceList=( $(chkconfig --list|gawk '{print $1}'|tr '\n' " ") );
if [ -n "$startList" ];then
for eachService in $startList
do
#将启用的服务从列表中删除
serviceList=( ${serviceList[@]#$eachService} );
#开启服务
serviceOn "$eachService" "on"
done;
#关闭服务
offList=${serviceList[@]};
if [ -n "offList" ];then
for eachOff in $offList
serviceOn "$eachOff" "off"
#主程序
function main()
s=$(dialog --separate-output --stdout --backtitle "服务管理" --checklist "请选择服务" 20 60 14 $(getService))
#按确认则开始
if [ $? -eq 0 ];then
manageService "$s"