脚本说明
- 此脚本的环境为centos , ubuntu下执行可能有问题
- 执行之前请安装expect yum -y install expect
- 把需要做互信的信息写入passwd.txt里面(非root,系统中需要存在该用户),一行一条记录,格式如下:IP 用户名 密码
- passwd.txt与sshkey.sh放在同一文件夹下
脚本内容
echo '#!/usr/bin/expect -f
set timeout 10
set ip [lindex $argv 0]
set username [lindex $argv 1]
set passwd [lindex $argv 2]
spawn ssh $ip -l $username
expect {
"yes/no" { send "yes\r";exp_continue }
"*assword:" { send "$passwd\r"; }
}
sleep 1
send "ssh-keygen -t rsa -P \"\" -f ~/.ssh/id_rsa \r"
sleep 1
send "scp /home/$username/.ssh/id_rsa.pub $username@hostip:/tmp/id_rsa$ip.pub\r"
expect {
"yes/no" { send "yes\r";exp_continue }
"*assword:" {send "$passwd\r"; }
}
sleep 1
send "exit\r"
sleep 2
send "exit\r"
sleep 2
expect eof'>ssh1
Hostip=`ifconfig eth0|grep -oP '(?<=inet addr:)\S+'`
sed -i "s/hostip/$Hostip/" ssh1
for i in `awk '{print $1}' passwd.txt`
do
j=`awk -v I="$i" '{if(I==$1)print $2}' passwd.txt`
k=`awk -v K="$i" '{if(K==$1)print $3}' passwd.txt`
expect ssh1 $i $j $k
done
cat /tmp/id_rsa*.pub >> /tmp/authorized_keys
chmod 600 /tmp/authorized_keys
echo '#!/usr/bin/expect -f
set timeout 15
set ip2 [lindex $argv 0]
set username2 [lindex $argv 1]
set passwd2 [lindex $argv 2]
sleep 1
spawn scp /tmp/authorized_keys $username2@$ip2:/home/$username2/.ssh/
expect {
"yes/no" { send "yes\r";exp_continue }
"*assword:" {send "$passwd2\r";}
}
expect eof' >scp2
for a in `awk '{print $1}' passwd.txt`
do
b=`awk -v A="$a" '{if(A==$1)print $2}' passwd.txt`
c=`awk -v B="$a" '{if(B==$1)print $3}' passwd.txt`
expect scp2 $a $b $c
done
sleep 1
rm -rf /tmp/id_rsa*.pub
sleep 1
rm -rf /tmp/authorized_keys
rm -rf ssh1
sleep 1
rm -rf scp2
exit