Files
devops/tools/ssh_key_push.sh
2025-06-26 16:35:19 +08:00

46 lines
1.2 KiB
Bash
Executable File
Raw 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
servers+=("$line")
done < "$file_path"
fi
# 推送公钥到远程服务器
for server in "${servers[@]}"; do
public_key=$(cat ~/.ssh/id_rsa.pub)
ssh "$server" "mkdir -p ~/.ssh && echo '$public_key' >> ~/.ssh/authorized_keys"
if [ $? -eq 0 ]; then
echo "公钥已成功推送到 $server"
else
echo "推送公钥到 $server 时出错。"
fi
done