我想在Centos7上使用shell脚本自动生成一对ssh密钥,我已经try 过了
yes "y" | ssh-keygen -t rsa
echo "\n\n\n" | ssh-keygen...
echo | ssh-keygen..
所有这些命令都不起作用,只需输入一个"enter",shell脚本就会在"enter passphrase(没有passphrase时为空)"上停止,
如果有人能帮忙,非常感谢!
我想在Centos7上使用shell脚本自动生成一对ssh密钥,我已经try 过了
yes "y" | ssh-keygen -t rsa
echo "\n\n\n" | ssh-keygen...
echo | ssh-keygen..
所有这些命令都不起作用,只需输入一个"enter",shell脚本就会在"enter passphrase(没有passphrase时为空)"上停止,
如果有人能帮忙,非常感谢!
我们需要自动完成two steps项:
Enter a passphrase.使用-N
标志(本例中为空字符串):
ssh-keygen -t rsa -N ''
Overwrite the key file:
使用-f
输入路径(在本例中为id_rsa
),再加上here-string回答yes以下问题:
ssh-keygen -q -t rsa -N '' -f ~/.ssh/id_rsa <<<y >/dev/null 2>&1
或者,在类似bash
的shell 下,如果使用certainly want to overwrite the previous one,只需使用here-string到feed the command,即可满足所有需要input:
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.
Step by step explanation
$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/klashxx/.ssh/id_rsa):
1)为避免输入 keys ,请使用-f
:
$ ssh-keygen -t rsa -f ~/.ssh/id_rsa
Generating public/private rsa key pair.
/home/klashxx/.ssh/id_rsa already exists.
是否覆盖(是/否)?
ATTENTION:如果您不关心RSA文件名,并且确实希望覆盖上一个文件名,请查看下面第四点的说明.
2)现在我们需要对overwrite question自动回答"y"(让我们用here-string来表示该作业(job)):
$ ssh-keygen -t rsa -f ~/.ssh/id_rsa <<< y
Generating public/private rsa key pair.
/home/klashxx/.ssh/id_rsa already exists.
是否覆盖(是/否)? 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.
是否覆盖(是/否)? 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
An alternative path to overwrite the previous RSA file (no -f flag needed)
NOTE:只有bash
个像贝壳.
如果您不关心RSA名称,只想覆盖它,我们需要自动回答以下两个问题:
输入保存密钥的文件:/example/path/.ssh/id_rsa已经存在.
是否覆盖(是/否)?
如果我们手工操作,第一个问题只需点击enter,第二个问题只需输入y
,然后按enter
.
我们可以使用以下here-string个参数来模拟这些动作:
$'\ny'
从bash
人页面:
对$'string'形式的单词进行了特殊处理.这个词扩展到
\新线
所以,如果我们用od
来分析字符串:
cat - <<< $'\ny' | od -c
0000000 \n y \n
我们看到我们得到了回答问题所需的东西.
Points 1 and 2 can be summarized into:
ssh-keygen -q -t rsa <<< $'\ny'
final command人将是:
$ ssh-keygen -q -t rsa -N '' <<< $'\ny' >/dev/null 2>&1
$ echo $?
0
Kudos
@卢卡斯·迪诺夫斯基、@redochka、@mellow yellow、@yeti和其他在这条线上的人.