1.编写脚本for1.sh,使用for循环创建20账户,账户名前缀由用户从键盘输入,账户初始密码由用户输入,例如: test1、test2、test3、.....、 test10
[root@server ~]# vim for1.sh
#!/bin/bash
read -p "请输入账户名前缀: " prefix
read -p "请输入账户初始密码: " password
for ((i=1; i<=20; i++)); do
username="${prefix}${i}"
if id "$username" &>/dev/null; then
echo "账户 $username 已存在"
else
useradd $username
if [ $? -eq 0 ]; then
echo -e "$password\n$password" | passwd $username
echo "账户 $username 创建成功"
else
echo "账户 $username 创建失败"
fi
fi
done
[root@server ~]# bash for1.sh执行脚本
2.编写脚本for2.sh,使用for循环,通过ping命令测试网段的主机连通性,IP前3段由用户输入,如: 输入192.168.48 ,则ping 192.168.48.125 - 192.168.48.135,将可以ping通的主机IP地址写入到 /tmp/host_up.txt文件中,不能ping通的主机IP地址写入到: /tmp/host_down.txt文件中
[root@server ~]# vim for2.sh
#!/bin/bash
read -p "请输入IP前三段: " ip_prefix
host_up_file="/tmp/host_up.txt"
host_down_file="/tmp/host_down.txt"
> /tmp/host_up.txt
> /tmp/host_down.txt
for ((i=134; i<=140; i++)); do
ip="${ip_prefix}.${i}"
ping -c 1 $ip >/dev/null
if [ $? -eq 0 ]; then
echo $ip >> /tmp/host_up.txt
else
echo $ip >> /tmp/host_down.txt
fi
done
3.使用for循环实现批量主机root密码的修改
(1) 打开多台主机
(2)使用ssh-keygen命令建立密钥对
(3)多台主机间通过ssh-copy-id进行免密登录
(4)编写脚本for3sh.通过for循环登录主机修改对方root账户密码
[root@server ~]# ssh-keygen -t rsa
[root@server ~]# ssh-copy-id root@192.168.19.135
[root@server ~]# ssh-copy-id root@192.168.19.136
[root@server ~]# vim for3.sh
#!/bin/bash
read -p "请输入密码:" passwd
for i in `cat ip.txt`
do
ssh $i "echo '$passwd' | passwd --stdin root"
done