(1)语法
(2)批量ping主机
这里有个重点就是把每次ping主机的动作放到后台运行
#!/bin/bash
>ip.txt
for i in {1..254}
do
ip=192.168.111.$i
{
ping -c1 -W1 $ip &>/dev/null
if [ $? -eq 0 ];then
echo "$ip is up!" | tee -a ip.txt
fi
}&
done
wait
echo "success"
(2)用户创建
重点:seq -w 10 会生成例如 01 02,前面使用0填充
#!/bin/bash
while true
do
read -p "please input prefix password number[bob 123456 10]" prefix password number
printf "user information:
----------------------------------
user prefix:$prefix
user password:$password
user number:$number
----------------------------------
"
read -p "Are you sure?[y|n]" action
if [ "$action" = y ];then
break
fi
done
for i in $(seq -w $number)
do
user=$prefix$i
id $user &>/dev/null
if [ $? -eq 0 ];then
echo "user $user is already exist!"
else
useradd $user
echo "$password" | passwd --stdin $user &>/dev/null
if [ $? -eq 0 ];then
echo "user $user is created!"
fi
fi
done
(3)实现文件中批量创建用户
重点:默认for循环是根据空白或tab键进行分割,这样对文件进行for循环,例如文件内容(jack01 123) 会把这一行当成两行内容,解决方案:使用IFS变量重新定义分割符
IFS=$'
'
#!/bin/bash
if [ $# -eq 0 ];then
echo "Usage: $(basename $0) file"
exit 1
fi
if [ ! -f $1 ];then
echo "error file!"
exit 2
fi
#希望for处理文件按回车分隔,而不是空格或tab空格
#重新定义分割符
#IFS=$'
'
IFS=$'
'
for line in $(cat $1)
do
user=$(echo $line |awk '{print $1}')
pass=$(echo $line |awk '{print $2}')
id $user &>/dev/null
if [ $? -eq 0 ];then
echo "user $user is already exists!"
else
useradd $user &>/dev/null
echo "$pass" | passwd --stdin $user
if [ $? -eq 0 ];then
echo "$user is created!"
fi
fi
done
用户文件内容如下,第一列是用户名,第二列是用户密码
jack01 123
jack02 456
jack03 789