任务要求:
一.编写脚本test4.sh,使用for循环创建20个账号,账户名前缀由用户从键盘输入,账户初始密码由用户输入
例如:test1、test2、test3、test4、test5、test6、test7、test8、test9、test10…test20
二.编写脚本test5.sh,使用for循环,通过ping命令测试网段的主机连通性,IP前3段由用户输入
如:输入192.168.182,则ping 192.168.182.125 - 192.168.182.140
将可以ping通的主机IP地址写入到/tmp/host_up.txt文件中,不能ping通的主机IP地址写入到:/tmp/host_down.txt文件中。
三.使用for循环实现批量主机root密码的修改
(1)打开多台主机
(2)使用ssh-keygen命令建立密钥对
(3)多台主机间通过ssh-copy-id进行免密登陆
(4)编写脚本test6.sh,通过for循环登陆主机修改对方root账户密码
1.编写脚本
[root@server ~]# vim test4.sh
#!/bin/bash
read -p "请输入账户的前缀:" prefix
read -p "请输入用户的账号密码:" passwd
for ((i=1;i<=20;i++))
do
user=Sprefix$i
if id $user &> /dev/null
then
echo "$uesr账户已存在"
else
useradd $user
if [ $? -eq 0 ]
then
echo "$passwd" | passwd --stdin $user &> /dev/
null
else
echo "用户创建失效"
exit
fi
fi
done
[root@server ~]# bash test4.sh
请输入账户的前缀:XiaoMing
请输入用户的账号密码:123456
测试脚本
XiaoMing1:x:1043:1043::/home/XiaoMing1:/bin/bash
XiaoMing2:x:1044:1044::/home/XiaoMing2:/bin/bash
XiaoMing3:x:1044:1044::/home/XiaoMing3:/bin/bash
XiaoMing4:x:1045:1045::/home/XiaoMing4:/bin/bash
......
2.编写脚本
[root@server ~]# vim test5.sh
#!/bin/bash
read -p "请输入网段:" ip
for ((i=125;i<=140;i++))
do
IP="$ip"."$i"
if ping -c 2 $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
[root@server ~]# bash test5.sh
请输入网段:192.168.186
up ip:
192.168.186.130 is up
down ip :
192.168.186.125 is down
192.168.186.126 is down
192.168.186.127 is down
192.168.186.128 is down
192.168.186.129 is down
192.168.186.131 is down
192.168.186.132 is down
192.168.186.133 is down
192.168.186.134 is down
192.168.186.135 is down
192.168.186.136 is down
192.168.186.137 is down
192.168.186.138 is down
192.168.186.139 is down
192.168.186.140 is down
3.编写保存多台主机ip地址文件
[root@server ~]# vim ip.txt
192.168.186.131
192.168.186.132
创建密钥
[root@server ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa
Your public key has been saved in /root/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:9m+BZoH1976gzA3WK0Gyaihk2Kd9H7rLxK1pQKpBtcU root@server
The key's randomart image is:
+---[RSA 3072]----+
| . |
| . E . |
| . o o . |
| . . . ..... . |
|. o o S +o . . |
| o = o...o+.o .|
| = + oo.=.o.+ . |
| . o oo=+ =o= o .|
| . +B+. =oo ..|
+----[SHA256]-----+
[root@server ~]# ssh-copy-id root@192.168.186.131
[root@server ~]# ssh-copy-id root@192.168.186.132
编写脚本
[root@server ~]# vim test6.sh
#!/bin/bash
read -p "please input your passwd:" ps
for i in `cat ip.txt`
do
ssh $i "echo "$ps" | passwd --stdin root"
done
运行脚本
[root@server ~]# bash test6.sh