在很多场景下,我们需要设置SSH密码登陆IP白名单,只允许特定的IP地址使用密码登陆。
首先,修改/etc/ssh/sshd_config配置文件,通过修改PasswordAuthentication全局关闭密码登录:
1 |
PasswordAuthentication no |
然后,在/etc/ssh/sshd_config配置文件的末尾添加Match:
Match的语法是:
1 2 3 |
Match condition Override config option 1 Override config option 2 |
其中的条件包括:
User – Specifies the user to match. For example, if user is root allow login with ssh-keys but disallow everyone else.
Group – Specifies the group to match. For example, If user in group admin, allow login but disallow everyone else.
Host – Specifies the host to match
Address – Specifies the IP address or IP/subnet to match in CIDR format.
因此我们可以在sshd_config的最后增加:
1 2 |
Match Address XXX.XXX.XXX.XXX PasswordAuthentication yes |
其中的XXX.XXX.XXX.XXX就是允许使用密码登陆的IP地址,即所谓的白名单。其含义为,当登录IP匹配XXX.XXX.XXX.XXX的形式时,允许采用密码登录。这里可以添加多个使用逗号分割的IP地址,也可以使用通配符、CIDR。
对于通配符而言:
* – It matches matches zero or more characters.
? – It matches exactly one character.
! – Patterns within pattern-lists may be negated with !.
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
## Match 192.168.1.1 to 192.168.1.9 ## Match Address 192.168.1.? PermitRootLogin yes ## Match 192.168.1.{2,3....} ## Match Address 192.168.2.* X11Forwarding no ## Allow any host in the ".home.lan" set of domains ## Match Host *.home.lan X11Forwarding yes ## Allow everyone except foo user ## Match User *,!foo X11Forwarding yes PermitTunnel yes PermitTTY no |
最后,重启sshd服务:
1 |
systemctl restart sshd |
我们就会发现之前能够使用密码登陆的机器已经不能登陆了:
参考资料:
1、https://www.cyberciti.biz/faq/match-address-sshd_config-allow-root-loginfrom-one_ip_address-on-linux-unix/
转载时请保留出处,违法转载追究到底:进城务工人员小梅 » SSH密码登陆IP白名单