1:编写脚本for1.sh,使用for循环创建20个账户,账户名前缀由用户从键盘输入,例如:test1,test2…
[root@server ~]# vim for1.sh
#/bin/bash
read -p "请输入账户名前缀:" prefix
read -p "请输入账户的密码:" passwd
for ((i=1;i<=20;i++))
do
user=$prefix$i
if id $user &> /dev/null
then
echo "$user已存在"
else
useradd $user
if [ $? -eq 0 ]
then
echo "$passwd" | passwd --stdin $user &> /dev/null
else
echo "用户创建失败"
exit
fi
fi
done
~
wq
[root@server ~]# bash for1.sh
[root@server ~]# cat /etc/passwd
cc:x:1000:1000:cc:/home/cc:/bin/bash
temp1:x:1001:1001::/home/temp1:/bin/bash
temp2:x:1002:1002::/home/temp2:/bin/bash
temp3:x:1003:1003::/home/temp3:/bin/bash
temp4:x:1004:1004::/home/temp4:/bin/bash
temp5:x:1005:1005::/home/temp5:/bin/bash
temp6:x:1006:1006::/home/temp6:/bin/bash
temp7:x:1007:1007::/home/temp7:/bin/bash
temp8:x:1008:1008::/home/temp8:/bin/bash
temp9:x:1009:1009::/home/temp9:/bin/bash
temp10:x:1010:1010::/home/temp10:/bin/bash
temp11:x:1011:1011::/home/temp11:/bin/bash
temp12:x:1012:1012::/home/temp12:/bin/bash
temp13:x:1013:1013::/home/temp13:/bin/bash
temp14:x:1014:1014::/home/temp14:/bin/bash
temp15:x:1015:1015::/home/temp15:/bin/bash
temp16:x:1016:1016::/home/temp16:/bin/bash
temp17:x:1017:1017::/home/temp17:/bin/bash
temp18:x:1018:1018::/home/temp18:/bin/bash
temp19:x:1019:1019::/home/temp19:/bin/bash
temp20:x:1020:1020::/home/temp20:/bin/bash
2 编写脚本for2.sh,使用for循环,通过ping命令测试网段的主机联通性,IP前三段由用户输入,如:192.168.6 则ping192.168.6.125-192.168.6.134,将可以ping的ip地址写入到/tmp/host_up.txt,不能ping通的写入到/tmp/host_down.txt 中。
[root@server ~]# vim for2.sh
#!/bin/bash
read -p "请输入网段:" ip
for ((i=125;i<=135;i++))
do
IP="$ip"."$i"
if ping -c 2 -w 3 $IP &> /dev/null
then
echo "$IP is up" >> /tmp/host_up.txt
else
echo "$IP is down" >> /tmp/host_down.txt
fi
done
echo "up ip: "
cat /tmp/host_up.txt
echo
echo "down ip :"
cat /tmp/host_down.txt
wq
[root@server ~]# bash for2.sh
请输入网段:192.168.6
up ip:
192.168.6.128 is up
192.168.6.130 is up
192.168.6.131 is up
down ip :
192.168.6.125 is down
192.168.6.126 is down
192.168.6.127 is down
192.168.6.129 is down
192.168.6.132 is down
192.168.6.133 is down
192.168.6.134 is down
3:使用for循环实现批量主机root密码的修改
(1)打开多台主机
(2)使用ssh-keygen命令建立密钥对
(3)多台主机间通过ssh-copy-id进行免密登录
(4)编写脚本for3.sh,通过for循环登录主机修改对方root账户密码
#建立免密登录
[root@server ~]# ssh-keygen -t rsa # 一路回车
[root@server ~]# ssh-copy-id root@192.168.48.131 # 输入yes及密码123
[root@server ~]# ssh-copy-id root@192.168.48.132 # 输入yes及密码123
#编写脚本
[root@server ~]# vim for3.sh
#!/bin/bash
read -p "请输入密码:" passwd
for i in `cat ip.txt` # 循环读取文本中的IP地址
do
ssh $i "echo '$passwd' | passwd --stdin root" # 远程登录修改密码
done
[root@server ~]# bash for3.sh
#更改ssh登录密码
请输入密码:666
Changing password for user root.
passwd: all authentication tokens updated successfully.
Changing password for user root.
passwd: all authentication tokens updated successfully.