Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SSH 免密登录 #20

Open
LLLeon opened this issue Jan 8, 2021 · 0 comments
Open

SSH 免密登录 #20

LLLeon opened this issue Jan 8, 2021 · 0 comments

Comments

@LLLeon
Copy link
Owner

LLLeon commented Jan 8, 2021

目标:通过 SSH 从 Server A 免密登录到 Server B。为了表述方便清晰,下面将 Server A 称为本地主机,将 Server B 称为远程主机。

方式:Public Key 认证。

原理:

  • 在本地主机上通过 ssh-keygen 生成一对密钥,简单说就是公钥用来加密,私钥用来解密(可扩展学习非对称加密)。
  • 将公钥拷贝到远程主机,然后在本地主机进行 SSH 连接。
  • 远程主机上的 sshd 会产生一个随机数并用上面的公钥进行加密后发给本地主机,本地主机会用私钥进行解密并把这个随机数发回给远程主机。
  • 远程主机的 sshd 会认为本地主机拥有与该公钥匹配的私钥,允许登录。

步骤:

主机系统为 CentOS 7。

  • 远程主机的 sshd 服务相关操作:

    systemctl status sshd
    systemctl start sshd
    systemctl stop sshd
    systemctl reload sshd

    需要在配置中启用公钥登录,vi /etc/ssh/sshd_config

    # 配置文件
    PubkeyAuthentication yes
    #PasswordAuthentication yes
  • 在本地主机生成一对密钥:

    ssh-keygen
  • 将公钥拷贝到远程主机,重命名 authorized_keys:

    scp id_rsa.pub root@ServerBIP:~/.ssh
    mv ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys

    或通过 ssh-copy-id 命令自动完成:

    ssh-copy-id -i ~/.ssh/id_rsa.pub root@ServerBIP
  • 本地主机向远程主机发送一个连接请求,信息包括用户名、IP:

    ssh root@serverBIP
  • 远程主机收到请求,会从 authorized_keys 中查找是否有相同的用户名、IP,如果有,它会随机生成一个字符串,并用公钥加密,然后发送给本地主机。

  • 本地主机收到远程主机发来的信息后,会使用私钥进行解密,然后将解密后的字符串发送给远程主机。

  • 远程主机收到本地主机发来的信息后,会和之前生成的字符串进行比对,如果一致,则允许免密登录。

使用:

  • 查看远程主机 IP 地址:

    ip addr
  • 登录:

    ssh root@ServerBIP

注意:

  • 将远程主机中 ~/.ssh 的权限设置为 700。
  • /.ssh/authorized_keys 的权限设置为 600。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant