如何在没有主目录的情况下存储 ssh 密钥?

如何在没有主目录的情况下存储 ssh 密钥?

remoteB我正在尝试从另一台服务器登录远程计算机,remoteA但我不想remoteB每次都输入密码。我想创建 SSH 密钥来执行此操作,但问题是我在 上没有主目录remoteA,只有remoteB.

我尝试.ssh在 A 上的(非主)目录内创建一个我可以访问的目录,但是当我这样做时

ssh-copy-id -i id_rsa.pub username@remoteB

然后它返回错误

Could not create directory '/home/name/.ssh'
The authenticity of host 'remoteB' can't be established

/home/这是有道理的,因为我在on中没有目录remoteA。但是有没有办法使用主目录以外的文件夹作为 SSH 密钥呢?

答案1

该消息Could not create directory '/home/test3/.ssh'.是警告,而不是错误。您可以将ssh密钥存储在任何安全的地方,但默认位置是您的主目录。

例如,本地用户test3没有主目录,但用户test4@otherhost有主目录。首先以用户 test3 身份在本地登录:

创建“安全”目录并生成证书对

mkdir -m700 /tmp/ssh
ssh-keygen -t rsa -f /tmp/ssh/id_rsa
Generating public/private rsa key pair.
...
Your public key has been saved in /tmp/ssh/id_rsa.pub.
...

尝试将其复制到目的地

ssh-copy-id -i /tmp/ssh/id_rsa.pub test4@otherhost
/usr/bin/ssh-copy-id: 59: cd: can't cd to /home/test3
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/tmp/ssh/id_rsa.pub"
The authenticity of host 'otherhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:pqNd/9gP69W2hzcosj+GI2DY2uw3+Upvvg22KV8sq5A.
Are you sure you want to continue connecting (yes/no)? yes
mktemp: failed to create file via template ‘/home/test3/.ssh/ssh-copy-id_id.XXXXXXXXXX’: No such file or directory
/usr/bin/ssh-copy-id: ERROR: mktemp failed

此时请注意安装失败,因此我们需要恢复到等效的手动流程。我们known_hosts也会将文件放在安全的地方,以免ssh每次使用时都会抱怨

ssh -o UserKnownHostsFile=/tmp/ssh/known_hosts test@otherhost 'mkdir -m700 -p .ssh && cat >>.ssh/authorized_keys' </tmp/ssh/id_rsa.pub
Could not create directory '/home/test3/.ssh'.
The authenticity of host 'otherhost (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:pqNd/9gP69W2hzcosj+GI2DY2uw3+Upvvg22KV8sq5A.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'otherhost' (ECDSA) to the list of known hosts.
Password:

这里有很多警告,但从根本上讲,这个过程已经成功了,密钥现在在远程帐户的authorized_keys文件中。让我们测试一下

ssh -o UserKnownHostsFile=/tmp/ssh/known_hosts -i /tmp/ssh/id_rsa test4@otherhost date
Could not create directory '/home/test3/.ssh'.
Thu 26 Nov 10:16:23 GMT 2020

我们从远程主机获得了一个日期字符串,因此我们可以证明它一切正常。

注意:每次使用时都ssh必须明确定义known_hosts文件以及id_rsa秘密

ssh -o UserKnownHostsFile=/tmp/ssh/known_hosts -i /tmp/ssh/id_rsa ...

相关内容