linux使用秘钥登录

warning: 这篇文章距离上次修改已过516天,其中的内容可能已经有所变动。

每次都忘记密码,得生成个密钥对来用,这样就方便不少了,也能防止密码泄露。

生成密钥对

ssh-keygen

在生成的时候,passphrase置空就可以实现无密码登录。

生成信息:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/ubuntu/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/ubuntu/.ssh/id_rsa
Your public key has been saved in /home/ubuntu/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:peKC/qZlWvJf8I7kqMcx+FvK5zamf8i0gR82JBNoC8U ubuntu@VM-0-10-ubuntu

授权公钥

密钥对生成之后, 要将公钥给服务器,然后持私钥链接。

cd /home/ubuntu/.ssh
cat id_rsa.pub >> authorized_keys

确保文件及目录权限:

chmod 600 authorized_keys
chmod 700 ~/.ssh

修改配置,打开秘钥登录

配置文件路径:/etc/ssh/sshd_config

PubkeyAuthentication yes

允许 root 账号登录:

PermitRootLogin yes

禁用密码登录:

PasswordAuthentication no

重启服务:

service sshd restart

使用

下载秘钥 id_rsa ,导入 xshell 中, 并输入对应的账号,即可使用。

注意事项

生成出来的秘钥默认是跟着 openssh 的版本,有些可能会不兼容。比如 jenkins 使用的就是 4096 长度的旧版本秘钥。因此在生成的时候要指定一下:

ssh-keygen -m PEM -t rsa -b 4096
none
最后修改于:2022年12月20日 22:43

评论已关闭