Linux Study Lab !

当前位置:   网站首页 >> Linux 基础配置

使用ssh证书验证登陆Linux (CentOS)

创建一个普通用户,具有默认bash权限的不要是nologin的。

useradd it
su it
ssh-keygen -t ed25519
>Generating public/private rsa key pair.
>Enter file in which to save the key (/home/it/.ssh/id_rsa):             //此处直接按回车保存在默认目录
>Created directory '/it/.ssh'.
>Enter passphrase (empty for no passphrase):                        //此处需要输入一个预共享密钥,由于我们有证书加持所以该密码可以不用非常复杂
>Enter same passphrase again: 
>Your identification has been saved in /home/it/.ssh/id_ed25519.             //生成的私钥
>Your public key has been saved in /home/it/.ssh/id_ed25519.pub.             //生成的公钥
cd /home/it/.ssh/
mv id_ed25519.pub authorized_keys                                                       //无论是root用户还是其他用户都必须修改文件名以便服务器识别验证文件

通过cat一下私钥的内容复制出来到本地ssh客户端电脑上,可以新建一个无后缀名的文件存放;或者使用sftp类软件下载下来

cat /home/it/.ssh/id_ed25519

接下来修改sshd配置:

vi /etc/ssh/sshd_config
PermitRootLogin prohibit-password       //默认是yes,改为root用户不能通过密码登陆
PubkeyAuthentication yes            //去掉注释,开启证书登陆
PasswordAuthentication no           //此处若定义no则ssh客户端在链接时不接受任何用户以密码登陆
AllowUsers [email protected] it                  //此处定义了只允许某个局域网段的root登陆请求,而it用户不限制
AddressFamily inet                              //此处定义sshd只监听ipv4地址,如需要监听v6则填写inet6,或保持默认值any
:wq保存
service sshd restart

接下来我们打开常用的ssh软件,这里举例用SecureCRT。

打开相应服务器的连接属性,左侧选择SSH2菜单,右侧的验证方式里将PublicKey优先级调整到最高或取消其他验证方式的勾。

blob.png

选择右侧的Properties...按钮,打开如下窗口,指定文件为你刚才下载的id_rsa

blob.png

确认OK即可,再次使用ssh连接服务器时,服务器会询问你私钥文件的预共享密码,也可以在生成私钥时不使用密码,从而仅凭证书登录。

如果同一台服务器上有多个ssh公钥的需求,比如gitlab等需求,可以生成多份key,不要混用登陆key文件,在生成新key文件时可以指定key的文件名以及路径,以及key的备注,如下:

ssh-keygen -t rsa -f ~/.ssh/id_rsa.gitlab -C "Key for Gitlab"

其中-f参数指定了文件路径和文件名,以避免覆盖原有的id_rsa文件,-C用于在文件内容末尾进行备注

特别注意,如果你没有使用root用户生成key,则文件默认不在/root/.ssh目录的情况下,不能使用chmod 400,而应该使用444权限,否则远端就无法再登陆验证了!

因为登陆验证默认只会去读取authorized_keys文件,为了实现多证书验证,在/root/.ssh目录下新建一个config文件,然后按实际情况填入如下内容

Host gitlab.com
    HostName gitlab.com
    IdentityFile  ~/.ssh/id_rsa.gitlab
    PreferredAuthentications publickey
    User root
    
Host github.com
    HostName github.com
    IdentityFile  ~/.ssh/id_rsa.github
    PreferredAuthentications publickey
    User root

User 定义的用户名是当前linux系统的用户名,默认使用root,如不是使用root用户运行的git提交,请自行修改。


发表我的评论

Hi,您需要填写昵称和邮箱!

  • 必填项
  • 必填项