1 编写脚本实现传入进程pid,查看对应进程/proc下的CPU、内存指标。
#!/bin/bash COLOR_RED_START="[1;31m" COLOR_RED_END="[0m" read -p "Please input the PID to check CPU&MEM infomation:" pid checkPid=`ps aux | awk '{print $2}' | grep -w "$pid"` if [ ! $checkPid ];then echo "The pid '$pid' does not exits, please make sure and input a correct pid. " else echo -e "\033${COLOR_RED_START}The MEM info is:\033${COLOR_RED_END}\n`sed -nr "/^Vm*/p" /proc/$pid/status`" echo -e "\033${COLOR_RED_START}The CPU info is:\033${COLOR_RED_END}\n`sed -nr "/^Cpu*/p" /proc/$pid/status`" echo -e "\033${COLOR_RED_START}The MEM PID_$pid uses is:\033${COLOR_RED_END} `ps -p $pid -o %mem | sed -n '2p'`" echo -e "\033${COLOR_RED_START}The CPU PID_$pid uses is:\033${COLOR_RED_END} `ps -p $pid -o %cpu | sed -n '2p'`" fi执行结果:
2 编写脚本实现每分钟检查一个主机端口是否存活(使用nmap),如果检查到端口不在线,sleep 10s, 如果三次都不存在,记录到日志。
#!/bin/bash ip=192.168.0.112 port=80 j=0 for (( i=0; i<3; i++ ));do status=`nmap $ip -p $port | sed -nr "s/^[0-9]+\/[a-z]+ ([a-z]+ ).*/\1/p"` if [ ! "$status" == "open" ];then sleep 10 let j++ else break fi done if [ $j -eq 3 ]; then echo "`date +"%F %T"` $ip:$port doesn't open." >> `pwd`/mylog/nmap.log fi [root@centos7 exercise]#crontab -e SHELL=/bin/bash * * * * * /root/exercise/scanPort.sh执行结果:
3 编写脚本/root/bin/execute.sh, 判断参数文件是否为sh后缀的普通文件,如果是,添加所有人可执行权限,否则提示用户非脚本文件。
#!/bin/bash [ $# -eq 0 ]||[ $# -gt 2 ]&& { echo "Usage: excute.sh file"; exit 1; } [ ! -f $1 ] && { echo "$1 does not exist or it's not a regular file."; exit 2; } [[ "$1" =~ \.sh$ ]] &&{ chmod +x $1;echo "$1 has been changed to be executable."; } || echo "$1 isn't a script."执行结果:
4 编写脚本/root/bin/nologin.sh和login.sh,实现禁止和允许普通用户登录系统。
vim nologin.sh [ ! -e /etc/nologin ] && { touch /etc/nologin; echo "Users have been forbidden to login."; } vim login.sh [ -e /etc/nologin ] && rm -f /etc/nologin && echo "Users can login now."
5 编写脚本/root/bin/sumid.sh,计算/etc/passwd文件中的第10个用户和第20个用户的ID之和。
#!/bin/bash id10=`cut -d: -f3 /etc/passwd|head -10|tail -1` id20=`cut -d: -f3 /etc/passwd|head -20|tail -1` let sumId=$id10+$id20 echo sumId is $sumId unset id10 id20 sumId