注意:ip.txt和send_ssh_key.sh必須在同一根目錄下bash
# 根據如下格式寫入服務器信息ip.txt,用於免密鑰登陸 #----------- # ip:password #192.168.1.110:7758521 #192.168.1.111:7758521 #192.168.1.112:7758521 #-----------
#!/bin/bash # 生成ssh key if [[ ! -f "/root/.ssh/id_rsa" ]];then echo "gen ssh key" ssh-keygen -t rsa -b 2048 -N '' -f /root/.ssh/id_rsa fi # 檢測是否安裝了 expect if ! expect -v &>/dev/null;then echo "install expect" yum install expect -y fi # 循環文件中的ip for p in $(cat ip.txt|grep -v '#');do ip=$(echo "$p"|cut -f1 -d":") # 取出當前IP password=$(echo "$p"|cut -f2 -d":") # 取出當前密碼 # expect 交互過程 expect -c " spawn ssh-copy-id -i /root/.ssh/id_rsa.pub root@$ip expect { \"*yes/no*\" {send \"yes\r\"; exp_continue} \"*password*\" {send \"$password\r\"; exp_continue} \"*Password*\" {send \"$password\r\";} } "