自动添加 ssh key 到远程主机的脚本,应用sshpass和ssh-copy-id

时间:2021-12-23 14:26:36

 

 

USERNAME=$1
PASSWORD=$2
HOST=$3

if [ "$3" = "" ]; then
  echo "Missing parameter 3 - host. Exit."
  exit 1
fi

if [ "$2" = "" ]; then
  echo "Missing parameter 2 - password. Exit."
  exit 1
fi

if [ "$1" = "" ]; then
  echo "Missing parameter 1 - username. Exit."
  exit 1
fi

if [ -f ~/.ssh/config ]; then
    grep StrictHostKeyChecking ~/.ssh/config
    exist=`echo $?`
    
    if [ ! "$exist" = "0" ]; then
      echo StrictHostKeyChecking no >> ~/.ssh/config
    fi
else
  echo StrictHostKeyChecking no >> ~/.ssh/config
fi

sshpass -p ${PASSWORD} ssh-copy-id -i ~/.ssh/id_rsa.pub ${USERNAME}@${HOST}

result=`echo $?`

if [ "$result" = "0" ]; then
  echo "Host ${HOST} is configured successfully."
else
  echo "Host ${HOST} configure failed."
fi