shell脚本案例
- 1、批量创建用户
- 2、资源检查
- 3、系统配置初始化
- 4、CPU、memory 消耗 top10
- 4、网卡流量监控
1、批量创建用户
#!/bin/bash
read -p "请输入要创建的用户名(空格隔开):" user_list
for user in $user_list;do
if ! id $user &> /dev/null;then
#给用户设置随机密码
pass=`echo $RANDOM | md5sum | cut -c 1-6`
useradd $user
echo $pass | passwd --stdin $user
echo "$user $pass" >> /opt/user_file
else
echo "$user user already exists!!!"
fi
done
2、资源检查
#!/bin/bash
cpu_check(){
cpu_util=`vmstat | awk 'NR==3 {print $13+$14"%"}'`
iowait=`vmstat | awk 'NR==3 {print $16"%"}'`
echo "---CPU使用情况---" && echo "cpu的使用率和等待磁盘IO响应使用率分别是: $cpu_util $iowait"
}
memory_check(){
memory_total=`free -h | awk 'NR==2 {print $2}'`
memory_used=`free -h | awk 'NR==2 {print $3}'`
memory_available=`free -h | awk 'NR==2 {print $NF}'`
echo "---内存使用情况---" && echo "内存总大小:$memory_total,已使用:$memory_used,剩余:$memory_available"
}
disk_check(){
Fs=`df -h | awk '/^/dev/ {print $1}'`
echo "---磁盘使用情况---"
for i in $Fs;do
fs=`df -h | awk -v x=$i '$1==x {print $1}'`
mounted=`df -h | awk -v x=$i '$1==x {print $NF}'`
size=`df -h | awk -v x=$i '$1==x {print $2}'`
used=`df -h | awk -v x=$i '$1==x {print $3}'`
used_percent=`df -h | awk -v x=$i '$1==x {print $5}'`
echo "Filesystem $fs挂载点为: $mounted,总大小: $size,已使用: $used,使用率: $used_percent"
done
}
tcp_status(){
tcp_status=`ss -antp | awk 'NR!=1 {x[$1]++}END{for(i in x)print i":"x[i]}'`
echo "---TCP连接状态---" && echo "$tcp_status"
}
cpu_check
memory_check
disk_check
tcp_status
3、系统配置初始化
#!/bin/bash
#减少swap使用,设置权重
echo "0" > /proc/sys/vm/swappiness
# 安装相关工具、软件包
yum -y install vim make wget gcc gcc-c++ net-tools zip sysstat iostat iftop iotp lrzsz
未完待续...
4、CPU、memory 消耗 top10
#!/bin/bash
#按照CPU使用率排序,会显示pid,cpu,memory,进程
echo "------------cpu top 10-------------------"
ps -eo pid,pcpu,pmem,args --sort=-pcpu | head
#按照内存使用率排序,会显示pid,cpu,memory,进程
echo "------------memory top 10-------------------"
ps -eo pid,pcpu,pmem,args --sort=-pmem | head
4、网卡流量监控
#!/bin/bash
#执行脚本时请指定要监控的网卡名称
eth=$1
echo "---------网卡进出流量监控中---------"
echo "--IN----------OUT--"
while true;do
#第一次取网卡进出的流量
IN_1=`cat /proc/net/dev | grep $eth | awk '{print $2}'`
OUT_1=`cat /proc/net/dev | grep $eth | awk '{print $10}'`
sleep 1
#第二次取网卡进出的流量
IN_2=`cat /proc/net/dev | grep $eth | awk '{print $2}'`
OUT_2=`cat /proc/net/dev | grep $eth | awk '{print $10}'`
#第二次减第一次网卡的差,不断循环,单位为 kb/s
IN=`printf "%.2f%s" "$((($IN_2-$IN_1)/1024))" "KB/s"`
OUT=`printf "%.2f%s" "$((($OUT_2-$OUT_1)/1024))" "KB/s"`
echo "$IN $OUT"
sleep 1
done