前提:
1. 保证需要做免密的机器网络互通,ssh端口防火墙彼此开放
2. 准备文件ip ,将需要做免密的主机ip和端口密码写入文件中并以【冒号】分割
ip:密码:端口
vim ssh.sh
#!/bin/bash
hostname="root"
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
执行方法:
chmod +x ssh.sh
sh ssh.sh
版权声明:本文为weixin_45782719原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。