-
ssh免密原理
执行 ssh-keygen -t rsa
/root/.ssh/ 生成 id_rsa 、id_rsd.pub
创建认证文件成功
cp /root/.ssh/id_rsa.pub /root/.ssh/authorized_keys
ssh-copy-id root@hostB
执行成功,hostB存在/root/.ssh/authorized_key文件
执行 ssh hostB ,链接成功。
-
ssh批量免密
前提:
1. 保证需要做免密的机器网络互通,ssh端口防火墙彼此开放
2. 准备文件ip ,将需要做免密的主机ip、密码、端口写入文件中并以【冒号】分割
ip:密码:端口
![](https://i-blog.csdnimg.cn/blog_migrate/cebd6185d0c6b5ed0eb9c28435bad4e8.png)
vim ssh.sh
#!/bin/bash
hostname="root"
#oldpw="AHdl@2021"
pub=~/.ssh/id_rsa.pub
#检查是否生成密钥
function key
{
expect <<EOF
spawn ssh-keygen
expect {
"/root/.ssh/id_rsa" { send "\n";exp_continue; }
"Enter passphrase" { send "\n";exp_continue;}
"again:" { send "\n";}
};
expect "fingerprint is:" {send "\n"} expect eof
EOF
}
#检查是否安装免交互命令
function exp
{
which expect
if [ $? == 0 ];then
echo "expect 已存在!"
else
echo "expect 不存在,正在安装..."
yum -y install expect
$expe
if [ $? == 0 ];then
echo "expect 已成功安装"
else
echo "expect 安装失败"
fi
fi
}
#做免密
function sshkey
{
expect <<EOF
spawn ssh-copy-id -p $3 $hostname@$1
expect {
"yes/no" { send "yes\n";exp_continue; }
"password" { send "$2\n";exp_continue;}
};
expect "]\#" {send "exit\n"} expect eof
EOF
}
#检查密码是否过期如果密码过期则修改密码
function ssh
{
expect <<EOF
spawn ssh -p $1 $hostname@$3
expect {
"(current) UNIX password:" { send "${oldpw}\n";exp_continue; }
"New password:" { send "$2\n";exp_continue;}
"Retype new password:" { send "$2\n";exp_continue;}
};
expect "]\#" {send "exit\n"} expect eof
EOF
}
exp
#监测密钥是否存在不存在则直接创建密钥
if [[ ! -f $pub ]];then
echo "密钥不存在,正在重新创建密钥..."
rm -rf ~/.ssh
key
[[ -f $pub ]]&& echo "密钥成功创建!!"
else
echo "密钥已存在!"
fi
#读取主机文件并做远程免密
while read line
do
for hosts in `echo ${line}`
do
for i in `echo "$hosts"`
do
host=`echo $i|awk -F: '{print $1}'`
pw=`echo $i|awk -F: '{print $2}'`
port=`echo $i|awk -F: '{print $3}'`
ssh ${port} ${pw} ${host}
sshkey ${host} ${pw} ${port}
done
done
done < ip