首先创建服务器配置文件,文件名:sship.txt
写入要配置免密的机器ip,
172.44.0.xx
172.44.0.xx
172.44.0.xx
注:一行一ip,密码必须统一一致
创建脚本文件,文件名:sshsetup.exp
写入内容:
#!/bin/bash
##!/usr/bin/expect
## use by root
## 给一个用户创建互信
## expect sshsetup.exp $user $password $home $ip_list_file
## expect sshsetup.exp gprds gp123 /data7/gprds ip.txt
## 0 1 2 3
set user [lindex $argv 0]
set password [lindex $argv 1]
set home [lindex $argv 2]
set host [lindex $argv 3]
set currdir [exec pwd]
exec rm -rf $currdir/ssh_out && rm -rf $currdir/authorized_keys
set fil [open $host r]
while {[gets $fil ip ]>=0} {
spawn ssh $user@$ip "rm -rf $home/.ssh/ && ssh-keygen -t rsa"
expect {
"*yes/no" {
send "yes\r"
exp_continue
}
"*assword" {
send "$password\r"
exp_continue
}
"*file in which to save the key*" {
send "\n\r"
send_user "$home/.ssh\r"
exp_continue
}
"*Enter passphrase*" {
send "\n\r"
exp_continue
}
"*Enter same passphrase again*" {
send "\n\r"
exp_continue
}
}
exec rm -rf $currdir/ssh_out
spawn scp -r $user@$ip:$home/.ssh/id_rsa.pub ssh_out
expect {
"*yes/no" {
send "yes\r"
exp_continue
}
"*assword" {
send "$password\r"
exp_continue
}
}
exec cat $currdir/ssh_out >> $currdir/authorized_keys
}
close $fil
exec rm -rf $currdir/ssh_out
set file [open $host r]
while {[gets $file ip ]>=0} {
spawn scp -r $currdir/authorized_keys $user@$ip:$home/.ssh/
expect {
"*yes/no" {
send "yes\r"
exp_continue
}
"*assword" {
send "$password\r"
exp_continue
}
}
spawn ssh $user@$ip "chmod 0600 $home/.ssh/authorized_keys "
expect {
"*yes/no" {
send "yes\r"
exp_continue
}
"*assword" {
send "$password\r"
exp_continue
}
}
}
close $file
启动脚本:
expect sshsetup.exp 免密用户 机器密码 免密用户文件位置如:/root sship.txt