在 Bash 中使用 Expect 创建用于用户身份验证的 SSH 密钥对

Creating an SSH Key Pair for User Authentication with Expect in Bash

我尝试了以下步骤来设置 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

为什么以及如何解决?

我会用 sshpass 来简化它。

#!/bin/bash
ip="x.x.x.x"
port="xx"
export SSHPASS="yyy"

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" || exit 1

sshpass -e ssh -oStrictHostKeyChecking=no -p "$port" "root@$ip" "mkdir -p -m 700 /root/.ssh"
sshpass -e scp -oStrictHostKeyChecking=no -P "$port" id_rsa.bwg_root.pub "root@$ip:/root/.ssh/authorized_keys"
sshpass -e ssh -oStrictHostKeyChecking=no -p "$port" "root@$ip" "chmod 640 .ssh/authorized_keys"

顺便说一句:我用 id_rsa.bwg_root.pub 替换了最后一个 id_rsa.pub 并将 -m 700 添加到 mkdir 并删除了 chmod 700 .ssh.

使用ssh-copy-id将新密钥推送到远程主机。 那个登录当然需要输入密码,但这是你最后一次使用它了。

#!/bin/bash
ip="x.x.x.x"
port="xx"
id_file=$HOME/.ssh/id_rsa_$ip

cat > $HOME/.ssh/config <<EOF
HOST $ip
IdentityFile $id_file
User root
EOF

ssh-keygen -t rsa -f "$HOME/.ssh/id_rsa_$ip" -q -b 2048 -N ""

ssh-copy-id -i "$id_file" -p "$port" root@"$ip"

作为一般规则,总是 在尝试 except 之前使用现有工具寻找非(或更少)交互式解决方案。