美文网首页
设置 SSH 通过密钥登录

设置 SSH 通过密钥登录

作者: Eafrey | 来源:发表于2019-07-17 00:13 被阅读0次

    使用一般的密码方式登录服务器的话,容易有密码泄露和被暴力破解的风险。所以一般会将 ssh 的端口设为 22 以外的端口或者禁用 root 账户登录。或者,更好的办法是,使用密钥的方式登录。

    设置使用密钥登录的几个步骤:

    1.在服务器上制作密钥对

    先采用密码登录的方式登录服务器,执行以下命令:

    [root@host ~]$ ssh-keygen  <== 建立密钥对
    Generating public/private rsa key pair.
    Enter file in which to save the key (/root/.ssh/id_rsa): <== 按 Enter
    Created directory '/root/.ssh'.
    Enter passphrase (empty for no passphrase): <== 输入密钥锁码,或直接按 Enter 留空
    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:
    0f:d3:e7:1a:1c:bd:5c:03:f1:19:f1:22:df:9b:cc:08 root@host
    

    密钥锁码在使用私钥时必须输入,这样就可以保护私钥不被盗用。当然,也可以留空,实现无密码登录。

    执行完上述命令后,在 root 用户的用户目录中会生成一个.ssh 的隐藏目录,内含两个密钥文件,其中id_rsa为私钥id_rsa.pub为公钥。

    2.在服务器安装公钥

    执行以下命令,将刚刚生成 的公钥 复制到 authorized_keys,完成公钥的安装

    [root@host ~]$ cd ~/.ssh
    [root@host .ssh]$ cat id_rsa.pub >> authorized_keys
    

    安装完成后需检查.ssh 目录和 authorized_keys 文件的权限

    [root@host .ssh]$ chmod 600 authorized_keys
    [root@host .ssh]$ chmod 700 ~/.ssh
    

    3.配置 ssh

    编辑 /etc/ssh/sshd_config 文件,添加以下配置项(如果配置过则更改以下配置项):

    RSAAuthentication yes
    PubkeyAuthentication yes
    

    同时 ,确保当前配置允许 root 用户登录:

    PermitRootLogin yes
    

    最后,重启 ssh 服务:

    [root@host .ssh]$ service sshd restart
    

    4.下载私钥

    通过 scp 拷贝密钥到本地当前目录:

    scp root@host:/root/.ssh/id_rsa ./
    

    最后,就可以通过密钥的方式 ssh 远程登录服务器了

     ssh -i ./id_rsa root@host
    

    如果登录的时候报“Permissions 0644 for './id_rsa' are too open.”,则需要将密钥文件的权限进行 修改:

    chmod 400 ./id_rsa
    

    然后尝试再次登录就可以了。

    相关文章

      网友评论

          本文标题:设置 SSH 通过密钥登录

          本文链接:https://www.haomeiwen.com/subject/skqflctx.html