目录
- 练习案例
- 1. for创建20用户
- 2. for ping测试指网段的主机
- 3. 使用for实现批量主机root密码的修改
练习案例
1. for创建20用户
用户前缀由用户输入
用户初始密码由用户输入
例如:test01,test10
#!/bin/bash
#########################
#File name:userCreate.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2023-01-03 15:48:18
#Description:
#########################
read -p "please input your username:" username
read -p "please input your userpasswd:" userpasswd
for i in {01..20}
do
user=$username$i
if ! id -u $user &>/dev/null
then
useradd $user
echo $userpasswd | passwd --stdin $user &>/dev/null
else
echo "then user is exists..."
fi
done
运行结果
[root@localhost homework4]# bash userCreate.sh
please input your username:xixi
please input your userpasswd:123
[root@localhost homework4]# cat /etc/passwd
2. for ping测试指网段的主机
网段由用户输入,例如用户输入192.168.2 ,则ping 192.168.2.10 — 192.168.2.20
UP: /tmp/host_up.txt
Down: /tmp/host_down.txt
#!/bin/bash
#########################
#File name:ping.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2023-01-03 15:57:46
#Description:
#########################
read -p "please input you test network:" net
for i in {10..20}
do
# echo $net.$i
ping -c 4 $net.$i &>/dev/null
if [ $? -eq 0 ]
then
echo "$net.$i is up" >> /tmp/host_up.txt
else [ $? -ne 0 ]
echo "$net.$i is down" >> /tmp/host_down.txt
fi
done
运行结果
[root@localhost homework4]# bash ping.sh
please input you test network:192.168.6
[root@localhost homework4]# cat /tmp/host_up.txt
192.168.6.20 is up
[root@localhost homework4]# cat /tmp/host_down.txt
192.168.6.10 is down
192.168.6.11 is down
192.168.6.12 is down
192.168.6.13 is down
192.168.6.14 is down
192.168.6.15 is down
192.168.6.16 is down
192.168.6.17 is down
192.168.6.18 is down
192.168.6.19 is down
3. 使用for实现批量主机root密码的修改
成功或失败都必须记录
提示:主机IP存放在一个文件中
SSH:实现公钥认证,执行远程中主机命令
实现公钥认证
#ssh-keygen 在用于管理的主上生成密钥对
#ssh-copy-id -i 192.168.2.3
ssh-keygen -f /root/.ssh/id_rsa -P '' -q $>/dev/null
for ip in `cat ipfile`
do
echo $ip
ssh-copy-copy-id root@$ip
done
for ip in `cat ipfile`
do
echo $ip
ssh root@ip "echo redhat | passwd --stdin root" &>/dev/null
if [ "$?" -eq 0 ]
then
echo "host $ip success update passwd" >> /tmp/ssh_success.txt
else
echo "host $ip error update passwd" >> /tmp/ssh_error.txt
fi
done