背景:服务器CentOS6.5;三台服务器:192.168.245.107;192.168.245.108;192.168.245.109;
用192.168.245.108为例,运行以下脚本内容。
目的:实现不用交互式生成公私钥;并在108上可以无密码登陆107和109;(注:对应不用用户更改路径)
脚本内容:
#!/bin/bash
oldpath=`$PWd`
echo $oldpath
yum install -y expect*
EXPECTMAKE(){
cat > expectssh.sh <<EOF
#!/usr/bin/expect -f
spawn ssh-keygen -t rsa
expect "*\(\/home\/scapp\/\.ssh\/id_rsa\):"
send "\r"
expect "*empty for no passphrase*"
send "\r"
expect "*same passphrase again:"
send "\r"
expect eof
EOF
expect -f expectssh.sh
}
########################################
if [ -d /home/scapp/.ssh ]
then
echo ".ssh haved maked"
cd /home/scapp/.ssh
if [ -f id_rsa ] || [ -f id_rsa.pub ]
then
rm -f id_rsa*
EXPECTMAKE
rm -f expectssh.sh
else
EXPECTMAKE
rm -f expectssh.sh
fi
cd $oldpath
else
mkdir /home/scapp/.ssh
chmod 755 /home/scapp/.ssh
cd /home/scapp/.ssh
if [ -f id_rsa ] || [ -f id_rsa.pub ]
then
rm -f id_rsa*
EXPECTMAKE
rm -f expectssh.sh
else
EXPECTMAKE
rm -f expectssh.sh
fi
cd $oldpath
fi
#进一步实现无密码相互登陆
cd /home/scapp/.ssh
echo "" > /home/scapp/.ssh/known_hosts
cat > 107.sh <<EOF
#!/usr/bin/expect -f
foreach i { 107 109 } {
spawn ssh-copy-id -i id_rsa.pub [email protected].\$i
expect "*connecting (yes\/no)\?"
send "yes\r"
expect "*password:"
send "你的密码\r"
expect eof
}
EOF
expect -f 107.sh
rm -f 107.sh
cd $oldpath
&&&&&改进&&&&&进一步实现无密码相互登陆
cd /home/scapp/.ssh
echo "" > /home/scapp/.ssh/known_hosts
cat > 107.sh <<EOF
#!/usr/bin/expect -f
set ipaddr [lindex \$argv 0]
spawn ssh-copy-id -i id_rsa.pub \$ipaddr
expect "*connecting (yes\/no)\?"
send "yes\r"
expect "*password:"
send "你的密码\r"
expect eof
EOF
for ipadd in `seq 1 100`
do
expect -f 107.sh [email protected].$ipadd
done
rm -f 107.sh
cd $oldpath