我想在Centos7上用shell脚本自动生成一对ssh key,我试过了
yes "y" | ssh-keygen -t rsa
echo "\n\n\n" | ssh-keygen...
echo | ssh-keygen..
所有这些命令都不起作用,只需输入一个“enter”,shell 脚本就会在“输入密码(为空表示没有密码)”处停止, 我只想知道如何在 shell 中连续模拟多个 'enter'。
如果有人能提供帮助,非常感谢!
最佳答案
我们需要自动完成两个步骤:
输入密码。使用
-N
标志(此示例为空字符串):ssh-keygen -t rsa -N ''
覆盖 key 文件:
使用 -f
输入路径(在本例中为 id_rsa
)加上一个 here-string 来回答 yes 以下问题:
ssh-keygen -q -t rsa -N '' -f ~/.ssh/id_rsa <<<y >/dev/null 2>&1
或者,在类似 shell 的 bash
下,如果您确实想覆盖以前的,只使用here-string < em>将所有需要的输入输入命令:
ssh-keygen -q -t rsa -N '' <<< $'\ny' >/dev/null 2>&1
来自 ssh-keygen
man 页面:
-N new_passphrase provides the new passphrase. -q silence ssh-keygen. -f filename specifies the filename of the key file.
一步一步的解释
$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/klashxx/.ssh/id_rsa):
1) 要避免输入 key ,请使用 -f
:
$ ssh-keygen -t rsa -f ~/.ssh/id_rsa
Generating public/private rsa key pair.
/home/klashxx/.ssh/id_rsa already exists.
Overwrite (y/n)?
注意:如果您不关心 RSA 文件名并且一定要覆盖之前的文件名,请查看以下第四点的说明。
2) 现在我们需要对覆盖问题自动回答“y”(让我们为该作业使用 here-string) :
$ ssh-keygen -t rsa -f ~/.ssh/id_rsa <<< y
Generating public/private rsa key pair.
/home/klashxx/.ssh/id_rsa already exists.
Overwrite (y/n)? Enter passphrase (empty for no passphrase):
3) 最后,我们将使用 -N
标志来输入无效通行证:
$ ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa <<< y
Generating public/private rsa key pair.
/home/klashxx/.ssh/id_rsa already exists.
Overwrite (y/n)? Your identification has been saved in /home/klashxx/.ssh/id_rsa.
Your public key has been saved in /home/klashxx/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:Xo0t6caMB/8TSsigxfY28JIfqYjyqxRZrFrPncx5yiU klashxx@server
The key's randomart image is:
+---[RSA 2048]----+
| |
| . |
| o . |
| + * = |
| +. + BSo= o |
|...o.+o+XO... |
|.. .o.E==+B. . |
|o . ...=.o... |
|.+o. o .. |
+----[SHA256]-----+
4) Extra ball,清理输出,只检查返回码:
$ ssh-keygen -q -t rsa -N '' -f ~/.ssh/id_rsa <<<y >/dev/null 2>&1
$ echo $?
0
覆盖先前 RSA 文件的替代路径(不需要 -f 标志)
注意:只有 bash
像 shell。
如果您不关心 RSA 名称,只想覆盖它,我们需要自动回答这两个问题:
Enter file in which to save the key: /example/path/.ssh/id_rsa already exists.
Overwrite (y/n)?
如果我们手动执行此操作,对于第一个问题,我们只需按 enter,对于第二个,键入 y
并按 enter
.
我们可以使用以下 here-string 来模拟这些操作:
$'\ny'
来自 bash
手册页:
Words of the form $'string' are treated specially. The word expands to "string", with backslash-escaped characters replaced as specified by the ANSI C standard.
\n new line
所以,如果我们使用 od
来分析我们的字符串:
cat - <<< $'\ny' | od -c
0000000 \n y \n
我们看到我们得到的正是我们需要回答的问题。
第 1 点和第 2 点可以概括为:
ssh-keygen -q -t rsa <<< $'\ny'
最终命令将是:
$ ssh-keygen -q -t rsa -N '' <<< $'\ny' >/dev/null 2>&1
$ echo $?
0
荣誉
@lukasz-dynowski、@redochka、@mellow-yellow、@yeti 和本帖中的其他人。
关于linux - 如何在没有提示的情况下执行 ssh-keygen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43235179/