1、使用 for 循环在 /www 目录下批量创建 10 个html 文件,名称为随机小写10个字母加日期

#!/bin/bash

if [ ! -d /opt/www ];then
mkdir -p /opt/www
fi

cd /opt/www

for i in `seq 10`
do
random=`echo $RANDOM | md5sum | cut -c 1-10 | tr "[0-9]" "[a-z]"`
touch $random"_"$(date +%Y%m%d)".html"
done
# 执行
[root@vm73 sh]# ll /opt/www
总用量 0
-rw-r--r-- 1 root root 0 2月 28 17:47 aedajffjcd_20200228.html
-rw-r--r-- 1 root root 0 2月 28 17:47 aifdadaicd_20200228.html
-rw-r--r-- 1 root root 0 2月 28 17:47 cbcajeejdd_20200228.html
-rw-r--r-- 1 root root 0 2月 28 17:47 cjafedjgca_20200228.html
-rw-r--r-- 1 root root 0 2月 28 17:47 dfecafafcf_20200228.html
-rw-r--r-- 1 root root 0 2月 28 17:47 ehghdjaadj_20200228.html
-rw-r--r-- 1 root root 0 2月 28 17:47 fabbccbffe_20200228.html
-rw-r--r-- 1 root root 0 2月 28 17:47 fjcbcjiiff_20200228.html
-rw-r--r-- 1 root root 0 2月 28 17:47 gfgjcfedag_20200228.html
-rw-r--r-- 1 root root 0 2月 28 17:47 jedcfaachf_20200228.html

2、批量创建 3个系统用户 xielong1~xieong3,密码随机10个字符串

#!/bin/bash

# 判断是否root用户
if [ $UID -ne 0 ];then
echo "only root run"
exit 1
fi

# 加载文件 . 点命令等同于 source
if [ -f /etc/init.d/functions ];then
. /etc/init.d/functions
fi

# 判断用户是否存在
isexist(){
result=$(grep -w "^$1" /etc/passwd | wc -l)

if [ $result -ne 0 ];then
echo "user $1 is exist!"
ret 1 "create user is failed"
continue
fi
}

ret(){
if [ $1 -eq 0 ];then
action "$2" /bin/true
else
action "$2" /bin/false
fi
}

# 产生用户
create(){
for i in $(seq -w 3)
do
user="xielong$i"
isexist $user
pass=$(cat /proc/sys/kernel/random/uuid | md5sum | cut -c 1-10)
useradd $user

if [ $? -eq 0 ];then
echo $pass | passwd --stdin $user &>/dev/null
ret 0 "create user $user is success"
fi

echo "$user $pass" >> /tmp/user.list

done
}

main(){
create
}

main

3、显示 192.168.2.0/24 网络里,有多少在线的 IP

#!/bin/bash

if [ -f /etc/init.d/functions ];then
. /etc/init.d/functions
fi

function ip_count(){
for ip in 192.168.2.{0..255}
do
status=`nmap -sP $ip | grep "Host is up" | wc -l`
if [ $status -eq 1 ];then
action "$ip" /bin/true
let i=i+1
fi
done
}

function main(){
ip_count
echo "The total number of online ip address is $i"
}

main

4、批量监控服务器磁盘利用率

# 主机信息
vim host.info

192.168.1.202 root 22
192.168.1.81 root 22
192.168.1.85 root 22


# 监控脚本
#!/bin/bash

host_info=host.info

for ip in $(awk '!/^#/{print $1}' $host_info); do
user=$(awk -v ip=$ip '{if(ip==$1){print $2}}' $host_info)
port=$(awk -v ip=$ip '{if(ip==$1){print $3}}' $host_info)

tmp_file=/tmp/disk.tmp
ssh -p $port $user@$ip 'df -h' > $tmp_file

use_rate_list=$(awk 'BEGIN{OFS="="}/^\/dev/{print $NF,int($5)}' $tmp_file)

for use_rate in $use_rate_list; do
partname=${use_rate%=*}
userate=${use_rate#*=}
if [ $userate -gt 20 ]; then
echo "warning: $ip host $partname partition usage $userate"
fi
done
done

# 运行
./check_disk.sh
warning: 192.168.1.202 host / partition usage 72
warning: 192.168.1.202 host /home partition usage 22
warning: 192.168.1.81 host /home partition usage 30
warning: 192.168.1.85 host / partition usage 74