分享一个Linux批量管理脚本--批量建立服务器之间SSH免密

发表于:2019-11-28 10:28

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:佚名    来源:波波说运维

  今天主要介绍一下linux如何批量建立SSH免密的过程,仅供参考。
  SSH免密
  一、批量建立ssh私钥认证
  1. 编译安装expect
  expect依赖于tcl,而linux系统里一般不自带安装tcl,所以需要手动安装。
  (1) 安装tcl
   cd /opt/tcl8.4.11/unix
  ./configure
  make && make install
  (2) 安装expect
   cd expect-5.43.0
  ./configure --with-tclinclude=/opt/tcl8.4.11/generic --with-tclconfig=/usr/local/lib/
  make && make install

  
  (3) 测试
  
  2. 主控端生成公钥
  执行ssh-keygen,该命令会默认在~/.ssh/目录下创建id_rsa、id_rsa.pub两个文件,分别为公钥和私钥
   ssh-keygen
  cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
  
  3. 相关脚本
  以下均放在/root目录下
  (1) ip.txt
  注意前面是IP,后面是密码,用冒号:分割,如果密码有冒号的建议单独处理
 IP:密码
  (2) remote_operate.sh
   #!/bin/bash
  #copyright by hwb
  if [ ! -d /root/.ssh ];then
  mkdir /root/.ssh
  fi
  cat /tmp/authorized_keys >> /root/.ssh/authorized_keys
  (3) batch_sshkey.sh
   #!/bin/bash
  #copyright by hwb
  for i in `cat ip.txt`
  do
  ip=$(echo "$i"|cut -f1 -d":")
  password=$(echo "$i"|cut -f2 -d":")
  expect -c "
  spawn scp /root/.ssh/authorized_keys /root/remote_operate.sh root@$ip:/tmp/
  expect {
  \"*yes/no*\" {send \"yes\r\"; exp_continue}
  \"*password*\" {send \"$password\r\"; exp_continue}
  \"*Password*\" {send \"$password\r\";}
  }
  "
  expect -c "
  spawn ssh root@$ip "/tmp/remote_operate.sh"
  expect {
  \"*yes/no*\" {send \"yes\r\"; exp_continue}
  \"*password*\" {send \"$password\r\"; exp_continue}
  \"*Password*\" {send \"$password\r\";}
  }
  "
  done
  4. 执行脚本并测试
  运行batch_sshkey.sh脚本
  

      本文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号