shell脚本配置ssh免密登陆
Posted 会飞的板儿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了shell脚本配置ssh免密登陆相关的知识,希望对你有一定的参考价值。
通过shell脚本配置免密登陆,分为两个脚本,一个是配置文件config.env,一个是正式脚本sshkey.sh。
# config.env
export HOST_USER=(root) export PASSWD=(a) export SSH_HOST=(192.168.165.15 192.168.165.16 192.168.165.165)
以上congfig.env文件中,SSH_HOST参数可配置多个IP,可配置不同的用户
sshkey.sh脚本内容大致如下:
- 在本地用rsa加密方式生成对应的密钥,并将公钥写入到authorized_keys文件中;
- 遍历多台远程服务器,登陆远程服务器生成密钥,并将公钥文件考本到本机,写入本机的authorized_Keys文件中;
- 遍历多台远程服务器,将本地的authorized_Keys文件分别分发到各台服务器上。
#!/bin/bash # sshkey.sh source config.env createLocalKey () { /usr/bin/expect <<_oo_ spawn ssh-keygen -t rsa -b 2048 -N "" -f $HOME/.ssh/id_rsa expect "Overwrite" send "y " expect eof _oo_ cat $HOME/.ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys } createRemoteKey () { /usr/bin/expect <<_oo_ spawn ssh [email protected]$ip expect { "yes/no" { send "yes ";exp_continue } "*assword:" { send "$PASSWD " } } sleep 1 send "ssh-keygen -t rsa -b 2048 -N ‘‘ -f $HOME/.ssh/id_rsa " expect { "(y/n)" { send "y " } } sleep 1 send "exit " expect eof _oo_ /usr/bin/expect <<_oo_ spawn scp [email protected]$ip:$HOME/.ssh/id_rsa.pub /tmp/id_rsa$ip.pub expect { "yes/no" { send "yes ";exp_continue } "*assword:" { send "$PASSWD " } } expect eof _oo_ cat /tmp/id_rsa$ip.pub >> $HOME/.ssh/authorized_keys rm -rf /tmp/id_rsa$ip.pub } copyToRemote () { /usr/bin/expect <<_oo_ spawn scp $HOME/.ssh/authorized_keys [email protected]$ip:$HOME/.ssh/authorized_keys expect { "yes/no" { send "yes ";exp_continue } "*assword:" { send "$PASSWD " } } expect eof _oo_ } pullPubKey () { for ip in ${MHA_HOST[@]};do if [ $ip == `ifconfig eth0|grep -oP ‘(?<=inet addr:)S+‘` ];then echo "It‘s local host" else createRemoteKey fi done } pushAuthorizedKeys () { for ip in ${MHA_HOST[@]};do if [ $ip == `ifconfig eth0|grep -oP ‘(?<=inet addr:)S+‘` ];then echo "It‘s local host" else copyToRemote fi done } taskMain () { createLocalKey pullPubKey pushAuthorizedKeys } red_echo () { [ "$HASTTY" == 0 ] && echo "[email protected]" || echo -e "