如何在Linux/Unix上更改或者更新SSH密钥密码

时间:2020-02-23 14:38:17  来源:igfitidea点击:

让我们看看如何在Linux系统上更新或者更改SSH密钥密码。 SSH密钥通常用于对某种信息系统的用户进行身份验证。 SSH密钥本身是私钥;使用派生自密码短语的对称加密密钥对私有密钥进行进一步加密。在Linux/Unix系统上更改SSH密钥密码很容易。

什么是SSH密钥密码?

密码类似于密码,用于保护SSH私钥免遭未经授权的访问和使用。始终建议为SSH密钥设置一个强大的密码短语,至少包含15个字符,最好是20个字符,并且很难猜到。

如何在Linux/Unix上更改或者更新SSH密钥密码

有时,我们可能需要更新SSH密钥密码,或者如果在生成SSH密钥时未设置,则设置一个。

例如,让我们生成不带密码的SSH密钥:

# ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:1gSD3mPgxaD0C88YLU+TdYs2T3nBO5ttK5Jj0bvz0gs theitroad@localhost
The key's randomart image is:
+---[RSA 2048]----+
|    . .++ ...    |
|   . +ooo= o..   |
|    =o*++ = ..   |
|     Xo++* .o    |
|    . =.S.o. =   |
|       .  . + o  |
|           oE+ . |
|          = =.o  |
|         . o.*o. |
+----[SHA256]-----+

现在,使用下面的命令来设置密码:

# ssh-keygen -p -f ~/.ssh/id_rsa
Enter new passphrase (empty for no passphrase): <Enter passphrase>
Enter same passphrase again:<Retype passphrase>
Your identification has been saved with the new passphrase.

如果使用自定义路径作为私钥,请将~/.ssh/id_rsa替换为私钥的路径。

重置密码时,将应用相同的命令,系统会要求我们输入旧密码和新密码。

# ssh-keygen -p -f ~/.ssh/id_rsa
Enter old passphrase: <Enter old passphrase>
Enter new passphrase (empty for no passphrase): <Enter new passphrase> 
Enter same passphrase again: <Retype new passphrase>
Your identification has been saved with the new passphrase.

测试新密码

要测试新密码是否正常工作,请将ssh公钥复制到远程服务器,然后尝试使用ssh。

$ssh-copy-id theitroad@localhost
Enter passphrase for key '/home/jmutai/.ssh/id_rsa': 
Now try logging into the machine, with "ssh 'theitroad@localhost'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.

保存私钥密码

使用ssh,我们可以将身份验证代理配置为保存密码,这样就不必在每次使用SSH密钥时都重新输入密码。

# Start agent on demand
eval $(ssh-agent) 

# Add default key
ssh-add 

# List keys
ssh-add -l 

# Add specific key
ssh-add ~/.ssh/id_rsa 

# Add with timeout
ssh-add -t 3600 ~/.ssh/id_rsa

# Drop keys
ssh-add -D