https://onitroad.com 更多教程

方法 2 - 使用 /etc/nologin 文件

这是阻止所有非 root 用户进行 SSH 登录的最快方法。

  1. 在远程主机上创建文件 /etc/nologin。
# touch /etc/nologin
# ls -lrt /etc/nologin
-rw-r--r-- 1 root root 0 Sep 13 13:23 /etc/nologin

注意:如果此文件存在,则只有 root 用户才能通过 SSH 登录系统。
如果文件 /etc/nologin.txt 存在,则 nologin 向用户显示其内容而不是默认消息。

确保以下行在文件 /etc/pam.d/sshd 中:

account    required     pam_nologin.so
Note: backup the file /etc/pam.d/sshd before modifying it.

然后重启sshd服务:

# service sshd restart
Stopping sshd:                                             [  OK  ]
Starting sshd:                                             [  OK  ]

验证非root用户SSH登录:

# ssh test@host1
test@host1's password: 
Connection closed by 192.168.10.10

方法 1 - 使用 /etc/ssh/sshd_config 文件

这种方法可以用于允许少数用户进行SSH登录。
编辑文件 /etc/ssh/sshd_config(OpenSSH SSH 守护程序配置文件)并添加关键字 AllowUsers 和参数 root 。

# vi /etc/ssh/sshd_config
AllowUsers root

注意:关键字不区分大小写,参数也区分大小写。

现在重启 sshd 服务:

# service sshd restart
Stopping sshd:                                             [  OK  ]
Starting sshd:                                             [  OK  ]

验证非 root 用户无法通过 SSH 登录,但 root 用户可以。

# ssh test@host1
test@host1's password: 
Permission denied, please try again.
test@host1's password: 
Permission denied, please try again.
test@host1's password: 
Permission denied (publickey,gssapi-with-mic,password).
# ssh root@host1
root@host1's password: 
Last login: Wed Sep 13 10:47:14 2017 from 10.10.10.10
[root@host1 ~]#

方法 3 - 使用 /etc/sshd/sshd.allow 文件

文件 /etc/sshd/sshd.allow 用于指定我们想要授予 ssh 访问权限的用户列表。
如果我们只是在这个文件中提到用户 root,那么所有其他用户都将被拒绝对主机的 ssh 访问。

  1. 在/etc/sshd/sshd.allow文件中添加root用户(如果目录/文件不存在,手动创建)。
# cat /etc/sshd/sshd.allow 
root
  1. 替换文件 /etc/pam.d/sshd 中的 auth 行如下:
auth required pam_listfile.so item=user sense=allow file=/etc/sshd/sshd.allow onerr=fail

其中:
auth required pam_listfile.so :验证用户时所需的模块的名称。

item=user :检查项目用户名。

sense=allow :允许用户。

file=/etc/sshd/sshd.allow :用户列表文件。

onerr=fail :如果用户名不在文件中,则不允许登录。

  1. 完成上述所有更改后,重新启动 sshd 服务。
# service sshd restart
Stopping sshd:                                             [  OK  ]
Starting sshd:                                             [  OK  ]
  1. 验证非root用户SSH登录:
# ssh test@host1
test@host1's password: 
Permission denied, please try again.
test@host1's password: 
Permission denied, please try again.
test@host1's password: 
Permission denied (publickey,gssapi-with-mic,password).

还要验证我们是否可以使用 root 用户 ssh:

# ssh root@host1
ssh root@host1's password: 
Last login: Wed Sep 13 14:53:47 2017 from 10.10.10.10
[root@host1 ~]#
CentOS/RHEL:如何禁止非 root 用户使用ssh

默认情况下,所有用户都可以使用有效的密码/公钥通过 SSH 进入系统。
对于某些具有特定角色的专用服务器,例如 FTP 服务器、电子邮件服务器等;通常建议禁用非 root 用户通过 SSH 登录。
该帖子详细介绍了禁用非 root 用户 ssh 登录访问系统的步骤。

这里讨论了 3 种不同的方式。
以下三种方式中的任何一种都可以达到目的。

日期:2020-09-17 00:12:14 来源:oir作者:oir