怎么限制某些IP访问服务器?

发布于:2025-07-05 ⋅ 阅读:(20) ⋅ 点赞:(0)

您可以通过多种方式限制特定IP地址访问您的服务器,以下是几种常见的方法:

1. 使用防火墙限制IP访问

Linux系统 (iptables)

# 阻止单个IP
iptables -A INPUT -s 192.168.1.100 -j DROP

# 阻止IP段
iptables -A INPUT -s 192.168.1.0/24 -j DROP

# 允许特定IP访问SSH(22端口)
iptables -A INPUT -s 203.0.113.5 -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j DROP

# 保存规则(根据系统不同)
iptables-save > /etc/sysconfig/iptables  # CentOS/RHEL
iptables-save > /etc/iptables/rules.v4   # Debian/Ubuntu

Linux系统 (ufw - Ubuntu)

sudo ufw deny from 192.168.1.100
sudo ufw allow from 203.0.113.5 to any port 22

Linux系统 (firewalld - CentOS/RHEL)

firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" reject'
firewall-cmd --reload

Windows系统

  1. 打开"高级安全Windows防火墙"

  2. 创建入站规则

  3. 选择"阻止连接"并指定要阻止的IP地址

2. 使用TCP Wrappers (Linux)

编辑/etc/hosts.deny文件:

sshd: 192.168.1.100
sshd: 192.168.1.0/24

编辑/etc/hosts.allow文件允许特定IP:

sshd: 203.0.113.5

3. 在服务配置中限制IP

SSH服务

编辑/etc/ssh/sshd_config

AllowUsers *@203.0.113.5
DenyUsers *@192.168.1.100

然后重启SSH服务:systemctl restart sshd

Nginx Web服务器

nginx

location / {
    deny 192.168.1.100;
    deny 192.168.1.0/24;
    allow 203.0.113.5;
    allow all;
}

Apache Web服务器

apache

<Directory "/var/www/html">
    Require all granted
    Require not ip 192.168.1.100
    Require not ip 192.168.1.0/24
</Directory>

4. 使用云服务商的安全组/ACL

AWS安全组

  1. 在EC2控制台选择安全组

  2. 编辑入站规则,添加拒绝规则

Azure网络安全组

  1. 在网络安全组中添加入站安全规则

  2. 设置源IP和操作(拒绝)

阿里云安全组

  1. 在ECS控制台配置安全组规则

  2. 添加拒绝特定IP访问的规则

5. 使用Fail2Ban自动阻止恶意IP

# 安装Fail2Ban
sudo apt install fail2ban  # Debian/Ubuntu
sudo yum install fail2ban  # CentOS/RHEL

# 配置(编辑/etc/fail2ban/jail.local)
[DEFAULT]
bantime = 1h
maxretry = 3

[sshd]
enabled = true

注意事项

  1. 修改防火墙规则前,确保不会把自己锁在服务器外

  2. 对于生产环境,建议先在测试环境验证规则

  3. 使用iptables -L -nufw status检查当前规则

  4. 定期审查IP限制列表,移除不再需要的限制

  5. 考虑使用IP黑名单和白名单结合的方式管理访问

以上方法可以根据您的具体需求和服务器环境选择使用或组合使用。


网站公告

今日签到

点亮在社区的每一天
去签到