Shell脚本(三)
一、使用for循环
1.使用for 循环创建用户
[root@centos01 ~]# vim username.sh
#!/bin/bash
user=$(cat ./username.txt)
for username in $user
do
useradd $username
echo "pwd@123" | passwd --stdin $username &> /dev/null
done
2.使用for循环删除用户
[root@centos01 ~]# vim deluser.sh
#!/bin/bash
user=$(cat ./username.txt)
for username in $user
do
userdel -r $username
done
3.使用for循环测试网络连通性
[root@centos01 ~]# vim ping.sh
#!/bin/bash
read -p "请输入指定的IP地址或主机名:" host
for ip in $host
do
ping -c 3 -i 0.2 -w 3 $ip &> /dev/null
if [ $? -eq 0 ]
then
echo "host $ip 主机开机!!"
else
echo "host $ip 主机关机!!"
fi
done
二、while循环
1.while循环创建用户
[root@centos01 ~]# vim whileadduser.sh
#!/bin/bash
prefix=stu
i=1
while [ $i -le 20 ]
do
useradd ${prefix}$i
echo "pwd@123" | passwd --stdin ${prefix}$1 &> /dev/null
let i++
done
增加执行权限
[root@centos01 ~]# chmod +x whileadduser.sh
执行
[root@centos01 ~]# ./whileadduser.sh
2.while循环删除用户
[root@centos01 ~]# cp whileadduser.sh whiledeluser.sh
[root@centos01 ~]# vim whiledeluser.sh
#!/bin/bash
prefix=stu
i=1
while [ $i -le 20 ]
do
userdel -r ${prefix}$i
let i++
done
[root@centos01 ~]# chmod +x whiledeluser.sh
[root@centos01 ~]# ./whiledeluser.sh
四、case服务控制
1.编写控制vsftpd
[root@centos01 ~]# vim vsftpd.sh
#!/bin/bash
#chkconfig:35 21 80
#description:vsftpd server
case "$1" in
start)
echo "正在启动vsftpd服务[确认]"
;;
stop)
echo "正在停止vsftpd服务[确认]"
;;
restart)
echo "正在重启vsftpd服务[确认]"
;;
*)
echo "使用语法:$0{ start | restart | stop }"
esac
[root@centos01 ~]# chmod +x vsftpd.sh
停止服务
[root@centos01 ~]# ./vsftpd.sh stop
启动服务
[root@centos01 ~]# ./vsftpd.sh start
重启服务
[root@centos01 ~]# ./vsftpd.sh restart