自动免密shell脚本

  • 确保每台机子的ip都配置成静态ip
  • 确保每台机子都能上网或者yum的源是本地源
  • 脚本前面内容的ip和网段自行更改成自已设置的ip以及服务器的密码也是如此
#!/bin/bash

password=123
hostnames=(master node1 node2)
ips=(110 111 112)
ip_prefix=192.168.1

if [ ! $(rpm -qa expect) ]
then
   yum install -y expect &>/dev/null
   [ $? -ne 0 ] && echo ">>>>>>>> install expect fail " && exit
fi

for ((i=0; i<${#ips[@]}; i++))
do
   str_commands+="$ip_prefix.${ips[$i]} ${hostnames[$i]}"
   str_hosts+="${hostnames[$i]}"
   if [ $i -lt $(( ${#ips[@]} -1 )) ]
   then
      str_commands+=" $'\n'"
	  str_hosts+="|"
   fi

done

for ((i=0; i<${#ips[@]}; i++))
do
expect <<-EOF
  spawn ssh root@$ip_prefix.${ips[$i]}
  expect {
    "(yes/no)?" {send "yes\r"; exp_continue}
    "password:" {send "$password\r"; exp_continue}
  }

  expect "#"
  send "rm -rf .ssh && mkdir .ssh\r"
  expect "#"
  send "sed -i -E '/$str_hosts/d' /etc/hosts \r"
  expect "#"
  send "echo -e $str_commands >> /etc/hosts \r"
  send "ssh-keygen -t rsa -P \"\" -f .ssh/id_rsa &>/dev/null \r"
  send "hostnamectl set-hostname ${hostnames[$i]}\r"
  expect "#"
  send "exit \r"
  expect eof
EOF
done

servers_str=$(IFS=" ";echo "${hostnames[*]}")

for ((i=0; i<${#ips[@]}; i++))
do
expect <<-EOF

  set servers [split "$servers_str" " "]

  spawn ssh root@$ip_prefix.${ips[$i]}
  expect {
    "(yes/no)?" {send "yes\r"; exp_continue}
    "password:" {send "$password\r"; exp_continue}
  }

  foreach server \$servers {
    expect "#"
    send "ssh-copy-id \$server \r"
    expect {
    "(yes/no)?" {send "yes\r"; exp_continue}
    "password:" {send "$password\r"; exp_continue}
    }
  }
  expect "#"
  send "exit\r"
  expect eof

EOF
done

timeout 5 ssh ${hostnames[0]} 'echo ">>>>>>>>> SSH has passwordless access! <<<<<<<<<<<"'
if [ $? -ne 0 ]
then
 'echo ">>>>>>>>> SSH has passwordless Fail! <<<<<<<<<<<"'
 exit 1
fi

for host in ${hostnames[@]}
do
ssh -T $host <<EOF
pgrep firewalld &>/dev/null
if [ \$? -eq 0 ]
then
   systemctl disable --now firewalld
fi

if [ ! "\$(getenforce)" = "Disabled" ]
then
   setenforce 0
   sed -i 's/^SELINUX=/cSELINUX=disabled' /etc/selinux/config
fi
sed -i 's|#UseDNS yes|UseDNS no|' /etc/ssh/sshd_config
systemctl restart sshd
exit
EOF
done

脚本执行完成后每台机子需要退出登录,重新登录一次,该脚本主机名更改之后需要在新的bash才能看到更改之后的效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值