一.环境介绍:
开启192.168.100.150-152(ctos1-3)和192.168.100.100(vsftpd)。
1.ssh登录:在192.168.100.100上操作
1)密码登录192.168.100.150:
ssh [email protected] ##输入root密码123123
2)配置ssh密钥对登192.168.100.150:
ssh-keygen ##创建密钥对,提示直接回车
ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected] ##输入root密码上传公钥
ssh [email protected] ##登录查看是否需要密码
ssh [email protected] "ifconfig eth0" ##在192.168.100.150上执行命令“ifconfig eth0”查看ip地址
3)删除相关信息,为ssh脚本测试做准备:
192.168.100.100上:rm -rf /root/.ssh/known_hosts
192.168.100.150上:rm -rf /root/.ssh
二.编写脚本批量操作主机名:
1.需求描述:
1)修改主机名:
将192.168.100.150的主机名修改为“www.linuxfan.cn”
将192.168.100.151的主机名修改为“ca.linuxfan.cn”
将192.168.100.152的主机名修改为“db.linuxfan.cn”
2)复制安全优化脚本“security.sh”到每台服务器上并执行。
3)security.sh要求实现:配置yum及yum更新系统,删除不必要的用户,关闭不必要的服务,设置防火墙默认规则,优化ssh配置,创建admin用户、初始密码123123并设置下次admin登录时必须修改密码且限制只允许该用户使用su命令,通过tcp wrapper设置只有192.168.100.100等登录。
2.编写脚本:
1)编写安全优化脚本:
vi security.sh
#!/bin/bash
相关知识学习完成后完成
useradd admin
echo 123123 |passwd --stdin admin
:wq
2)编写批量操作脚本:
[[email protected] bin]# cat ssh-changename.sh
#!/bin/bash
#by linuxfan.cn 2016-9-24
##set variable
export PRE="192.168.100."
export PW="123123"
export HNF="/etc/sysconfig/network"
#create and security ssh pair key for ssh connect.
for i in {150,151,152};do
/usr/bin/expect <<EOF
spawn ssh-copy-id [email protected]$PRE$i
expect {
"(yes/no)?" { send "yes\r"; exp_continue }
"password:" { send "$PW\r" }
}
interact
expect eof
EOF
export CMD="ssh [email protected]$PRE$i"
##change hostname.
ping -c 2 $PRE$i &>/dev/null
SETVAL=$?
if [ $i -eq 150 ] && [ $SETVAL -eq 0 ];then
$CMD "sed -i ‘s/^HOST.*/HOSTNAME=www.linuxfan.cn/g‘ $HNF "
##create test file and make dir.
$CMD "touch /tmp/public-key-test.txt;mkdir -p /root/bin" &>/dev/null
##copy security.sh to host and exec it.
scp /root/bin/security.sh [email protected]$PRE$i:/root/bin &>/dev/null
$CMD "source /root/bin/security.sh" &>/dev/null
elif [ $i -eq 151 ] && [ $SETVAL -eq 0 ];then
$CMD "sed -i ‘s/^HOST.*/HOSTNAME=ca.linuxfan.cn/g‘ $HNF "
##create test file and make dir.
$CMD "touch /tmp/public-key-test.txt;mkdir -p /root/bin" &>/dev/null
##copy security.sh to host and exec it.
scp /root/bin/security.sh [email protected]$PRE$i:/root/bin &>/dev/null
$CMD "source /root/bin/security.sh" &>/dev/null
elif [ $i -eq 152 ] && [ $SETVAL -eq 0 ];then
$CMD "sed -i ‘s/^HOST.*/HOSTNAME=mysql.linuxfan.cn/g‘ $HNF "
##create test file and make dir.
$CMD "touch /tmp/public-key-test.txt;mkdir -p /root/bin" &>/dev/null
##copy security.sh to host and exec it.
scp /root/bin/security.sh [email protected]$PRE$i:/root/bin &>/dev/null
$CMD "source /root/bin/security.sh" &>/dev/null
else
echo "$PRE$i is down, Please check and try again."
exit 1
fi
done
[[email protected] bin]#
3)测试:
分别在三台主机上查看:
id admin
cat /etc/sysconfig/network