Skip to content

Instantly share code, notes, and snippets.

@ssrlive
Last active February 18, 2022 04:38
Show Gist options
  • Save ssrlive/2d9344ba983cc5e51a56684c9f93552b to your computer and use it in GitHub Desktop.
Save ssrlive/2d9344ba983cc5e51a56684c9f93552b to your computer and use it in GitHub Desktop.
ssh 公钥私钥登录的实际流程

ssh 公钥私钥登录的实际流程

客户端建立私钥和公钥

在客户端终端运行命令

ssh-keygen -t rsa

rsa 是一种密码算法,证书登录常用 rsa。

假设用户是 blue, 执行 ssh-keygen 时,才会在 我的home 目录底下的 .ssh/ 这个目录里面产生所需要的两把 Keys ,分别是私钥 (id_rsa) 与公钥 (id_rsa.pub)。

另外就是私钥的密码了,如果不是测试,不是要求无密码 ssh,那么对于 passphrase,不能输入空(直接回车),要妥当想一个复杂的密码。

命令行讲解

ssh-keygen -t rsa -b 4096 -f ~/.ssh/user_ca -C user_ca

上面的命令会在~/.ssh目录生成一对密钥:user_ca(私钥)和user_ca.pub(公钥)。

这个命令的各个参数含义如下。

  • -t rsa:指定密钥算法 RSA。
  • -b 4096:指定密钥的位数是4096位。安全性要求不高的场合,这个值可以小一点,但是不应小于1024。
  • -f ~/.ssh/user_ca:指定生成密钥的位置和文件名。
  • -C user_ca:指定密钥的识别字符串,相当于注释,可以随意设置。

ssh 服务端配置

ssh服务器配置, 编辑ssh配置文件 vim /etc/ssh/sshd_config 如下:

#禁用root账户登录,非必要,但为了安全性,请配置
PermitRootLogin no

# 是否让 sshd 去检查用户家目录或相关档案的权限数据,
# 这是为了担心使用者将某些重要档案的权限设错,可能会导致一些问题所致。
# 例如使用者的 ~.ssh/ 权限设错时,某些特殊情况下会不许用户登入
StrictModes no

# 是否允许用户自行使用成对的密钥系统进行登入行为,仅针对 version 2。
# 至于自制的公钥数据就放置于用户家目录下的 .ssh/authorized_keys 内
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile      %h/.ssh/authorized_keys

#有了证书登录了,就禁用密码登录吧,安全要紧
PasswordAuthentication no

配置好 ssh 服务器的配置了,那么我们就要把 客户端的公钥 上传到服务器端,然后把 客户端的公钥 添加到 authorized_keys

在客户端执行命令

scp ~/.ssh/id_rsa.pub blue@<ssh_server_ip>:~

在服务端执行命令

cat  id_rsa.pub >> ~/.ssh/authorized_keys

如果有修改配置 /etc/ssh/sshd_config ,需要重启 ssh 服务器

/etc/init.d/ssh restart

客户端通过私钥登录 ssh 服务器

ssh 命令

ssh -i ~/.ssh/id_rsa blue@<ssh_server_ip>

如果在这里报告私钥文件 too open 拒绝登录,可以执行以下命令更改私钥性质再来。

chmod 600 ~/.ssh/id_rsa

scp 命令

scp -i ~/.ssh/id_rsa filename blue@<ssh_server_ip>:/blue

每次敲命令,都要指定私钥,是一个很繁琐的事情,所以我们可以把私钥的路径加入 ssh 客户端的默认配置里

修改 /etc/ssh/ssh_config

#其实默认id_rsa就已经加入私钥的路径了,这里只是示例而已
IdentityFile ~/.ssh/id_rsa
#如果有其他的私钥,还要再加入其他私钥的路径
IdentityFile ~/.ssh/blue_rsa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment