ansible-devops/scripts/auto_ssh_auth_setup.sh

114 lines
3.3 KiB
Bash
Raw Normal View History

2025-10-30 20:04:18 +08:00
#!/bin/bash
# 初始化变量
ip_file=""
target_user=""
target_pass=""
# 解析命令行参数
while [[ $# -gt 0 ]]; do
case "$1" in
--file=*)
ip_file="${1#*=}"
shift
;;
--user=*)
target_user="${1#*=}"
shift
;;
--passwd=*)
target_pass="${1#*=}"
shift
;;
*)
echo "错误:未知参数 $1"
echo "使用方法:$0 --file=ip.txt --user=用户名 --passwd=密码"
exit 1
;;
esac
done
# 参数校验
if [[ -z "$ip_file" || -z "$target_user" || -z "$target_pass" ]]; then
echo "错误:参数不完整"
echo "使用方法:$0 --file=ip.txt --user=用户名 --passwd=密码"
exit 1
fi
# 检查IP文件是否存在且可读
if [[ ! -f "$ip_file" || ! -r "$ip_file" ]]; then
echo "错误IP文件 $ip_file 不存在或无法读取"
exit 1
fi
# 检查IP文件是否为空
if [[ ! -s "$ip_file" ]]; then
echo "错误IP文件 $ip_file 内容为空"
exit 1
fi
# 检查sshpass是否安装用于自动输入密码
if ! command -v sshpass &> /dev/null; then
echo "错误未安装sshpass请先安装后再执行"
echo "Ubuntu/Debian: sudo apt-get install -y sshpass"
echo "CentOS/RHEL: sudo yum install -y sshpass"
exit 1
fi
# 生成本地SSH密钥对如果不存在
echo "正在生成本地SSH密钥对..."
mkdir -p ~/.ssh
if [[ ! -f ~/.ssh/id_rsa ]]; then
ssh-keygen -t rsa -f ~/.ssh/id_rsa -N '' -q <<< y 2>/dev/null
else
echo "本地密钥对已存在,跳过生成步骤"
fi
# 配置本地SSH客户端避免首次连接确认
echo "配置本地SSH客户端..."
cat > ~/.ssh/config << EOF
Host *
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
EOF
# 设置目录和文件权限
chmod 700 ~/.ssh
chmod 600 ~/.ssh/config
touch ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
# 批量分发公钥到目标主机(核心修复:添加< /dev/null避免抢占输入流
echo "开始向目标主机分发公钥..."
while IFS= read -r ip; do
# 跳过空行
[[ -z "$ip" ]] && continue
echo "处理主机: $ip"
# 步骤1在目标主机创建.ssh目录并设置权限重定向输入到/dev/null
if ! sshpass -p "$target_pass" ssh -o ConnectTimeout=10 "$target_user@$ip" \
"mkdir -p ~/.ssh && chmod 700 ~/.ssh" < /dev/null; then
echo "警告:无法在 $ip 创建.ssh目录跳过该主机"
continue
fi
# 步骤2将本地公钥复制到目标主机临时文件重定向输入到/dev/null
if ! sshpass -p "$target_pass" scp -o ConnectTimeout=10 ~/.ssh/id_rsa.pub \
"$target_user@$ip:~/.ssh/temp_pub_key" < /dev/null; then
echo "警告:无法将公钥复制到 $ip,跳过该主机"
continue
fi
# 步骤3将临时公钥追加到authorized_keys并清理重定向输入到/dev/null
if ! sshpass -p "$target_pass" ssh -o ConnectTimeout=10 "$target_user@$ip" \
"cat ~/.ssh/temp_pub_key >> ~/.ssh/authorized_keys && rm -f ~/.ssh/temp_pub_key && chmod 600 ~/.ssh/authorized_keys" < /dev/null; then
echo "警告:无法在 $ip 配置authorized_keys跳过该主机"
continue
fi
echo "成功配置 $ip 的免密登录"
done < "$ip_file"
echo "所有主机处理完成"