Files
devops/tools/ssh_key_push.sh
2025-07-21 11:39:05 +08:00

75 lines
2.4 KiB
Bash
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
: << 'EOF'
配置主机之间的信任关系使得scpssh 等可以免密登陆
EOF
# 检查本地是否存在 id_rsa.pub
if [ ! -f ~/.ssh/id_rsa.pub ]; then
echo "本地未找到 id_rsa.pub开始生成新的 SSH 密钥对..."
ssh-keygen -t rsa -b 4096 -C "oscar@easyprompt8.com" -N "" -f ~/.ssh/id_rsa
if [ $? -eq 0 ]; then
echo "SSH 密钥对生成成功。"
else
echo "生成 SSH 密钥对时出错。"
exit 1
fi
fi
# 处理服务器列表
# bash push_ssh_key.sh user1@server1 user2@server2
if [ $# -gt 0 ]; then
servers=("$@")
else
echo "请提供包含服务器列表的文件路径:"
read file_path
if [ ! -f "$file_path" ]; then
echo "文件 $file_path 不存在。"
exit 1
fi
servers=()
while IFS= read -r line; do
# 跳过空行和注释行
[[ -z "$line" || "$line" =~ ^# ]] && continue
servers+=("$line")
done < "$file_path"
fi
# 推送公钥到远程服务器
public_key=$(cat ~/.ssh/id_rsa.pub)
for server in "${servers[@]}"; do
# 第一次尝试推送
echo "正在推送公钥到 $server..."
output=$(ssh "$server" "mkdir -p ~/.ssh && echo '$public_key' >> ~/.ssh/authorized_keys" 2>&1)
exit_code=$?
if [ $exit_code -eq 0 ]; then
echo "公钥已成功推送到 $server"
continue
fi
# 检测是否是主机密钥验证失败
if echo "$output" | grep -q "Host key verification failed"; then
echo "检测到 $server 的主机密钥已变更,正在清理旧密钥..."
# 提取主机地址(处理 user@host 格式,取 @ 后面的部分)
host=$(echo "$server" | cut -d'@' -f2)
# 清理旧密钥
cleanup_output=$(ssh-keygen -R "$host" 2>&1)
if [ $? -ne 0 ]; then
echo "清理 $host 旧密钥失败:$cleanup_output"
continue
fi
echo "已清理 $host 的旧密钥,重新尝试推送..."
# 重新推送
retry_output=$(ssh "$server" "mkdir -p ~/.ssh && echo '$public_key' >> ~/.ssh/authorized_keys" 2>&1)
retry_code=$?
if [ $retry_code -eq 0 ]; then
echo "公钥已成功推送到 $server"
else
echo "重新推送 $server 失败:$retry_output"
fi
else
# 其他错误类型
echo "推送 $server 失败:$output"
fi
done