批量自动建立linux服务器之间的ssh互信


介绍:我们在部署无密码访问时,如果手工输入.很费时间.下面方法用于自动化生成authorized_keys,免去了手工数据.
方法: 利用expect编写sshkey.exp在远程主机上生成id_rsa,并重定向到本地.在利用noscp.exp.把文件复制到远程主机
步骤:(本方法在centos6.4 上验证通过)

1 本地执行
ssh-keygen -t rsa

2 编写脚本生成 authorized_keys (比如现在有cloud1 和 cloud2 服务器)

./sshkey.exp  cloud1 root root123 | grep ssh-rsa >> ~/.ssh/authorized_keys
./sshkey.exp  cloud2 root root123 | grep ssh-rsa >> ~/.ssh/authorized_keys


3 对于需要建立免密码输入的,把文件拷贝上去

./noscp.exp ~/.ssh/authorized_keys cloud1:~/.ssh root root123
./noscp.exp ~/.ssh/authorized_keys cloud2:~/.ssh root root123


4. 脚本说明
./sshkey.exp  主机名 用户名  密码  (在远程主机生成id_rsa)
./noscp.exp   本地文件 远程路径  远程用户密码   (无密码拷贝文件)
 
注意:
 每个主机上必须安装 openssh-clients

#!/usr/bin/expect

#sshkey.exp

if {$argc<3} {
 puts stderr "Usage: $argv0 host  user  passwd "
 exit 1
}

set host [ lindex $argv 0 ]
set user  [ lindex $argv 1 ]
set pwd  [ lindex $argv 2 ]

set timeout 30

 

#spawn ssh ${user}@${host} "rm -rf ~/.ssh/id_rsa*"
#
#expect {
# "*yes/no" { send "yes\r"; exp_continue }
# "*password:" { send "$pwd\r"; exp_continue  }
#}


spawn ssh ${user}@${host} "ssh-keygen -t rsa"

expect {
 "*yes/no" { send "yes\r"; exp_continue }
 "*password:" { send "$pwd\r"; exp_continue  }
 "Enter file in which to save the key*" { send "\n\r"; exp_continue }
 "Overwrite*" { send "y\n"; exp_continue }
 "Enter passphrase (empty for no passphrase):" { send "\n\r"; exp_continue }
 "Enter same passphrase again:" { send "\n\r" }
}

spawn ssh ${user}@${host} "cat ~/.ssh/id_rsa.pub"

expect {
 "*yes/no" { send "yes\r"; exp_continue }
 "*password:" { send "$pwd\r"  }
}

expect eof

 

#!/usr/bin/expect

#noscp.exp

if {$argc<4} {
 puts stderr "Usage: $argv0 localfile  remotefile user passwd "
 exit 1
}

set localfile [ lindex $argv 0 ]
set remotefile  [ lindex $argv 1 ]
set user  [ lindex $argv 2 ]
set pwd  [ lindex $argv 3 ]

set timeout 30

spawn scp ${localfile} ${user}@${remotefile}

expect {
 "*yes/no" { send "yes\r"; exp_continue }
 "*password:" { send "$pwd\r" }
}

expect eof

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值