您的位置:首页 > 其它

expect实现配置机器信任关系

2014-05-31 17:06 429 查看
利用expect的交互功能,自动配置信任机器之间的信任关系。

代码里会判断机器是否生成了秘钥,如果没有生成过,则自动帮助你执行 ssh-keygen

#!/bin/sh

expect_ssh_copy_id()
{
if [ "$#" -ne "5" ]; then
echo "expect_ssh_copy_id <remoteUser> <remoteHostname> <password> <localUserhome> <timeout>";
exit 1;
fi
local remoteUser=$1
local remoteHostname=$2
local password=$3
local localUserhome=$4
local timeout=$5

expect -c "
set timeout $timeout
spawn ssh-copy-id -i $localUserhome/.ssh/id_rsa.pub $remoteUser@$remoteHostname
expect {
\"*yes/no\" { send \"yes\r\"; exp_continue }
\"*assword:\" { send \"$password\r\" }
}
expect eof
"

}

expect_ssh_keygen()
{
if [ "$#" -ne "2" ]; then
echo "expect_ssh_keygen <localUserhome> <timeout>";
exit 1;
fi
local localUserhome=$1;
local timeout=$2;
if [ -f ${localUserhome}/.ssh/id_rsa.pub -a -f ${localUserhome}/.ssh/id_rsa ] ; then
echo "$(remoteHostname) is already create id_rsa.pub and id_rsa"
else
echo "$(remoteHostname) is not set id_rsa.pub and id_rsa.pub"
expect -c "
set timeout $timeout
spawn ssh-keygen
expect {
\"*save the key*id_rsa*\" {send \"\r\"; exp_continue }
\"*verwrite*y/n*\" { send \"y\r\"; exp_continue }
\"*passphrase*passphrase*\" { send \"\r\"; exp_continue }
\"*same passphrase*\" {send \"\r\" }
}
expect eof
exit 0
"
if [ "$?" -eq "0" ] ; then
echo "create id_rsa.pub,id_rsa successfully"
else
echo "create id_rsa.pub,id_rsa faild"
fi
fi

}
configure_trust_relation()
{
if [ "$#" -ne "5" ]; then
echo "configure_trust_relation <remoteUser> <remoteHostname> <password> <localUserhome> <timeout>";
exit 1;
fi
local remoteUser=$1
local remoteHostname=$2
local password=$3
local localUserhome=$4
local timeout=$5

expect -c "

set timeout $timeout
set trust true

#
# checking remote machine is be trusted
# if trust, return 0
# if not trust, return 1
#
spawn ssh $remoteUser@$remoteHostname

expect {
\"*yes/no\" { send \"yes\r\" ; exp_continue }
\"*assword:\" { send \"$password\r\" ; set trust false }
}

expect { *\$* }

send \"exit\r\"
sleep 1
if { \"\$trust\" == \"false\"} {
expect eof
exit 1
}
expect eof
exit 0
"
if [ "$?" -ne "0" ] ; then
echo "machine is not be trusted, then exec ssh-copy-id to remote machine"
expect_ssh_keygen $localUserhome $timeout
expect_ssh_copy_id $remoteUser $remoteHostname $password $localUserhome $timeout
else
echo "remote machine is be trusted"
fi
}

main()
{
which expect
if [ "$?" -ne "0" ]; then
echo "expect is not exists"
exit 1;
fi
remoteUser=chen;
remoteHostname=localhost;
password=chen;
localUserhome=$(cd ~;pwd;);
timeout=5;

configure_trust_relation $remoteUser $remoteHostname $password $localUserhome $timeout

}

main
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: