#!/bin/bash os_user= os_password= hosts=' '#多个ip用空格分隔 id $os_user >/dev/null || exit 1 #获取用户家目录 user_home=$(grep -w $os_user /etc/passwd |cut -d : -f 6) # 生成ssh从stdin读取免密的脚本 cat > /tmp/pass << EOF #!/bin/bash [[ $1 =~ password: ]] && cat || SSH_ASKPASS="$0" DISPLAY=nothing:0 exec setsid "$@" EOF chmod a+x /tmp/pass # 生成密钥文件 su - $os_user -c "echo $USER; mkdir -p -m 700 .ssh; [ -f .ssh/id_rsa ] && echo '已存在私钥文件 .ssh/id_rsa' || { ssh-keygen -t rsa -f .ssh/id_rsa -P '' >/dev/null && echo '生成私钥文件 .ssh/id_rsa' || echo '生成私钥文件失败' ;}" # 获取密钥内容 id_rsa=$(cat $user_home/.ssh/id_rsa) id_rsa_pub=$(cat $user_home/.ssh/id_rsa.pub) for host in $hosts; do echo "$host: " echo "$os_password" | /tmp/pass ssh -o StrictHostKeyChecking=no $os_user@$host "mkdir -p .ssh; chmod 700 .ssh; echo '$id_rsa' > .ssh/id_rsa && chmod 600 .ssh/id_rsa echo '$id_rsa_pub' > .ssh/id_rsa.pub && chmod 644 .ssh/id_rsa.pub echo '$id_rsa_pub' > .ssh/authorized_keys && chmod 600 .ssh/authorized_keys " su - $os_user -c "ssh -o StrictHostKeyChecking=no $os_user@$host 'hostname|| exit 1' " && echo '成功' || echo '失败' done