【发布时间】:2019-12-17 23:06:03
【问题描述】:
我已尝试以下步骤设置 ssh 无密码(SSH 密钥对身份验证)登录。
在 bash 中设置 ip 和端口。
ip="xxxx"
port="xxxx"
在客户端设置 ssh 配置文件
cat > $HOME/.ssh/config <<EOF
Host $ip
IdentityFile $HOME/.ssh/id_rsa
User root
EOF
在客户端创建一个 ssh 密钥对
ssh-keygen -t rsa -f $HOME/.ssh/id_rsa -q -b 2048 -N ""
将 id_rsa 从客户端推送到 ssh 服务器。
准备ssh服务器
ssh -p $port root@$ip "mkdir -p /root/.ssh"
将授权文件推送到ssh服务器
scp -P $port id_rsa.pub root@$ip:/root/.ssh/authorized_keys
为授权文件设置权限
ssh -p $port root@$ip "chmod 700 .ssh; chmod 640 .ssh/authorized_keys"
成功了!
现在我想将所有步骤写入作业的一键式 bash 脚本。
这是我的尝试。
#! /bin/bash
ip="xxxx"
port="xxxx"
pass="yyyy"
cat > $HOME/.ssh/config <<EOF
Host $ip
IdentityFile $HOME/.ssh/id_rsa.bwg_root
User root
EOF
ssh-keygen -t rsa -f $HOME/.ssh/id_rsa.bwg_root -q -b 2048 -N ""
cd $HOME/.ssh
/usr/bin/expect <<EOF
spawn ssh -p $port root@$ip "mkdir -p /root/.ssh"
expect "password:"
send "$pass\r"
spawn scp -P $port id_rsa.pub root@$ip:/root/.ssh/authorized_keys
expect "password:"
send "$pass\r"
spawn ssh -p $port root@$ip "chmod 700 .ssh; chmod 640 .ssh/authorized_keys"
expect "password:"
send "$pass\r"
EOF
得到以下输出信息:
spawn ssh -p xxxx root@yyyy mkdir -p /root/.ssh
root@yyyy's password: spawn scp -P xxxx id_rsa.bwg.pub root@yyyy:/root/.ssh/authorized_keys
root@yyyy's password: spawn ssh -p xxxx root@yyyy chmod 700 .ssh; chmod 640 .ssh/authorized_keys
为什么以及如何解决它?
【问题讨论】: