如何配置自动化的免密登录?

如何实现执行脚本,输入IP/用户名/密码/端口,就能实现免密登录对方设备

已邀请:

主脚本内容:

#!/bin/bash


script_path=$(cd "$(dirname "$0")";pwd)
cat ~/.ssh/id_rsa.pub > /dev/null 2>&1
if [[ $? -ne 0 ]]; 
then 
  echo "在~/.ssh/并未发现秘钥文件,自动生成"
  cd ~/.ssh/
  ssh-keygen -t rsa -N '' -f id_rsa -q 
fi

read -p "请输入目标服务器IP:" node_ip
read -p "请输入用户名:" username
read -p "请输入密码:" password
read -p "请输入端口:" port


cd $script_path

function setTrust(){
    ip=$1
    user=$2
    passwd=$3
    port=$4
    if [[ "${port}" == "" ]];then
        port=22
    fi
    ping -c 1 -W 1 ${ip} > /dev/null 2>&1
    if [[ $? -ne 0 ]]; then echo "${ip}....连接失败"; exit 2; fi
    #注意:${script_path}/config/exp/setTrust.exp替换成自己的目录文件

    expect ${script_path}/setTrust.exp "$ip" "$user" "$passwd" "$port" > /dev/null 2>&1
    if [[ $? -ne 0 ]]; then echo "${ip}....免密失败(可能是密码错误)"; exit 2; fi
    test -f /tmp/scp__test.test || touch -f /tmp/scp__test.test
    scp -P ${port} /tmp/scp__test.test ${user}@${ip}:/tmp/ > /dev/null 2>&1
    echo "${ip}....免密成功"
}


setTrust "${node_ip}" "${username}" "${password}" "${port}"

附.setTrust.exp内容

#!/bin/expect
# 简单命令执行
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
set sshport [lindex $argv 3]

set timeout 10


spawn ssh-copy-id -f -o ConnectTimeout=3 -p ${sshport} ${user}@${ip}
expect {
"*(yes/no)?" {send "yes\r";exp_continue}
"*password:" {send "$password\r";exp_continue}
"*Permission denied*" { exit 1 }
}


要回复问题请先登录注册