脚本配置:ssh-agent密钥管理器

无口令漫游

###############################################
cat > ~/hosts.txt<.0.0.102 root a123456!
10.0.0.103 root a123456!
10.0.0.104 root a123456!
EOF
chmod 600 ~/hosts.txt
###############################################
cat > ~/ssh-agent.sh << EOF
#!/bin/bash
##
## 创建ssh私钥/公钥对
rmp -qa | grep expect || yum install -y expect
/usr/bin/expect << END
spwan ssh-keygen
expect {
"*:"      {send "\r";  exp_continue}
"*(y/n)?" {send "n\r"; exp_continue}
eof
}
END
##
## 开启ssh-agent代理,并托管ssh私钥
cat > /etc/profile.d/ssh-agent.sh << END
#!/bin/bash
if [ -f ~/.agent.env ]; then
   . ~/.agent.env >/dev/null
   if ! kill -0 \\\$SSH_AGENT_PID >/dev/null 2>&1;then
      echo "Stale agent file found.Spawning new agent..."
      eval \\\$(ssh-agent | tee ~/.agent.env)
      ssh-add
   fi
else
   echo "Starting ssh-agent..."
   eval \\\$(ssh-agent | tee ~/.agent.env)
   ssh-add
fi
END
source /etc/profile
##
##开启ssh-agent代理转发功能
sed -r -i -e '/^[ \t]*#[ \t]* ForwardAgent /c ForwardAgent yes' /etc/ssh/ssh_config
systemctl restart sshd
##
##将ssh公钥传给远程主机,并且开启远程主机的ssh-agent代理转发功能
cat ~/hosts.txt | while read var_host; do
    var_host_name=\`echo "\${var_host}" | awk '{print \$1}'\` && echo "\${var_host_name}"
    var_host_user=\`echo "\${var_host}" | awk '{print \$2}'\` && echo "\${var_host_user}"
    var_host_pass=\`echo "\${var_host}" | awk '{print \$3}'\` && echo "\${var_host_pass}"
    /usr/bin/expect <<END
        spawn ssh-copy-id \${var_host_user}@\${var_host_name}
        expect {
                "*(yes/no)?" {send "yes\r";exp_continue}
                "*password:" {send "\${var_host_pass}\r";exp_continue}
                eof
        }
END
ssh \${var_host_user}@\${var_host_name} <<END
        sed -r -i -e '/^[ \t]*#[ \t]* ForwardAgent /c ForwardAgent yes' /etc/ssh/ssh_config
        systemctl restart sshd
END
done
reboot
EOF
#################################################3
bash ~/ssh-agent.sh

你可能感兴趣的:(笔记)