常用的shell脚本案例(14.04.15更新)

编写shell脚本的思路

1、思考需要实现什么功能
2、用什么命令、方法实现此功能
3、写shell代码
4、将此.sh文件写入/root/.bash_profile 登陆文件中



###CPU 内存 网络 存储IO###########
#!/bin/bash
mkdir -p /var/log/runrec
RecFile="/var/log/runrec/running.today"
RecTime=`date +"%Y-%m-%d %H:%M"`
LoadRec=`uptime`
MemRec=`free -m`
LastLoginRec=`last -n 20`
x=`ps aux | wc -l`
proNum=`expr $x - 1`
usage=` df -hT | grep "/$" | awk '{print $6}'`
echo"++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Record Time: $RecTime
cpu Load information:$LoadRec
Memory information:$MemRec
Last login 20 users record:$LastLoginRec
running process : $proNum
usage of / filesys: $usage">> $RecFile





###查看服务状态\重启等######
#!/bin/bash 
/etc/init.d/$1 status/stop/start/restart/reload


#! /bin/bash
/sbin/service httpd status &> /dev/null
if [ $? -ne 0 ] ; then
echo "httpd is down.at time: `date`" >> /var/log/htmon.log
/sbin/service httpd restart
/sbin/service httpd status &>/dev/null
fi

############检测FTP服务是否开启
#!/bin/bash
TARGET=$(awk'{print $1}' /etc/ethers)
echo"follow is anonymous FTP server:"
for IP in $TARGET
do
 wget –T 3  -t 3 ftp://$IP/ &> /dev/null
		if [ $? -eq0 ] ; then
 			echo $IP
		fi
done
参数提示:-T 连接超时时间;-t 连接重试次数










####搜集网卡MAC地址
#!/bin/bash
NADD="192.168.4."
FILE="/etc/ethers"
[-f $FILE ] && /bin/cp -f $FILE $FILE.old
HADD=1
while[ $HADD -lt 4 ]
do
	arping -c 2 -w 1 ${NADD}${HADD} &>/dev/null
		if [ $? -eq0 ] ; then
  		arp -n | grep ${NADD}${HADD} | awk '{print$1,$3}' >> $FILE
		fi
	let HADD++
done






#########批量添加用户
要求提供交互功能,当管理员执行该脚本时,可以根据提示指定需添加的用户数量(少于100)、用户名前缀、并能够设置这些用户账户的失效时间,初始密码。
用户名编号统一使用两位数,如使用”01”、”02”、”03”的形式,而不是”1”、”2”、”3”的形式。
编写对应的批量删节除用户脚本,要能够通过命令行参数指定用户名前缀,执行脚本后删除所有使用了该前缀的用户账户,但要防止删除root用户。
批量添加用户脚本:
1、批量添加用户脚本myuadd.sh内容如下:
#!/bin/bash
read-p "input nu <1-99>:" nu
read-p "input name:" name
read-p "input date <YYYY-MM-DD>:" date
read-p "input password:" password
a=1
if[ $nu -lt 100 ]
then
		while[ $a -le $nu ]
			do
				if [ $a -lt 10 ]
					then
					useradd -e $date"$name"0"$a"
					echo "$password" | passwd--stdin "$name"0"$a" &>/dev/null
				else
					useradd -e $date"$name""$a"
     echo "$password" | passwd--stdin "$name""$a" &>/dev/null
				fi
				a=`expr$a + 1`
			done
fi




######批量删除用户脚本:
1、批量删除用户脚本myudel.sh内容如下:
#!/bin/bash
if[ $# -le 0 ] ; then
echo "error:the prefix of users has notbe specified."
echo "usage:$0 nameprefix"
exit 1
fi
tarjcvf /root/users.cnf.tar.gz /etc/passwd /etc/shadow /etc/group &>/dev/null
tobedel=`grep"$1" /etc/passwd | cut -d ":" -f 1 | grep -v"root"`
for u in $tobedel
do
userdel -r $u &> /dev/null
done


你可能感兴趣的:(常用的shell脚本案例(14.04.15更新))