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

时间:2022-10-14 10:19:19


介绍:我们在部署无密码访问时,如果手工输入.很费时间.下面方法用于自动化生成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