互信是指配置免密登录另一台主机,常用于自动化脚本!
以下分享个互信脚本:
dest_user=$1
password=$2
hosts_file=$3
if [ $# -ne 3 ]; then
echo "usage:"
echo "$0 remoteuser remotepassword hostsfile"
exit 1
fi
if [ "${dest_user}" != "root" ]; then
cd /home/"${dest_user}"/ || return
fi
ssh_dir=~/.ssh
script_prefix=./tmp
echo ===========================
# 1. prepare directory .ssh
mkdir $ssh_dir
chmod 700 $ssh_dir
# 2. generat ssh key
tmp_script=$script_prefix.sh
{
echo "#!/usr/bin/expect"
echo "spawn ssh-keygen -b 1024 -t rsa"
echo "expect *key*"
echo "send \r"
} >>$tmp_script
if [ -f $ssh_dir/id_rsa ]; then
{
echo "expect *verwrite*"
echo "send y\r"
} >>$tmp_script
fi
{
echo "expect *passphrase*"
echo "send \r"
echo "expect *again:"
echo "send \r"
echo "interact"
} >>$tmp_script
chmod x $tmp_script
/usr/bin/expect $tmp_script
rm -rf $tmp_script
# 3. generat file authorized_keys
cat $ssh_dir/id_rsa.pub >>$ssh_dir/authorized_keys
# 4. chmod 600 for file authorized_keys
chmod 600 $ssh_dir/authorized_keys
echo ===========================
# 5. copy all files to other hosts
for ip in $(<"${hosts_file}"); do
if [ "x$ip" != "x" ]; then
echo -------------------------
tmp_script=${script_prefix}.$ip.sh
# check known_hosts
val=$(ssh-keygen -f "${ip}")
if [ "x$val" == "x" ]; then
echo "$ip not in $ssh_dir/known_hosts, need to add"
val=$(ssh-keyscan "${ip}" 2>/dev/null)
if [ "x$val" == "x" ]; then
echo "ssh-keyscan $ip failed!"
else
echo "${val}" >>$ssh_dir/known_hosts
fi
fi
echo "copy $ssh_dir to $ip"
{
echo "#!/usr/bin/expect"
echo "spawn scp -r $ssh_dir $dest_user@$ip:~/"
echo "expect *assword*"
echo "send $password\r"
echo "interact"
} >"$tmp_script"
chmod x "$tmp_script"
/usr/bin/expect "$tmp_script"
rm -rf "$tmp_script"
echo "copy done."
fi
done
# 6. date ssh
for ip in $(<"$hosts_file"); do
if [ "x$ip" != "x" ]; then
{
echo "#!/usr/bin/expect"
echo "spawn ssh $dest_user@$ip date"
echo "expect *yes*"
echo "send yes\r"
echo "interact"
} >"$tmp_script"
chmod x "$tmp_script"
/usr/bin/expect "$tmp_script"
rm -rf "$tmp_script"
echo "copy done."
fi
done
创建一个脚本 sshtrust.sh
,将以上内容写入脚本!
支持多台主机进行互信,创建一个 sshhostlist.cfg
文件,将需要配置互信的主机ip写入:
10.211.55.100
10.211.55.101
10.211.55.102
执行如下命令互信:
sh sshtrust.sh 互信用户 互信用户密码 sshhostlist.cfg
执行完成后,即配置互信成功!
本次分享到此结束啦~
如果觉得文章对你有帮助,点赞、收藏、关注、评论,一键四连支持,你的支持就是我创作最大的动力。
❤️ 技术交流可以 关注公众号:lucifer三思而后行 ❤️
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【米乐app官网下载的版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。