linux

Linux虚拟机中如何配置防火墙

小樊
40
2025-06-25 03:21:32
栏目: 云计算

在Linux虚拟机中配置防火墙,通常使用的是iptablesfirewalld。以下是两种常见的方法:

使用 iptables

  1. 查看当前规则

    sudo iptables -L -n -v
    
  2. 允许特定端口(例如,允许SSH访问):

    sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
    
  3. 允许HTTP和HTTPS访问

    sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
    sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
    
  4. 拒绝所有其他输入

    sudo iptables -P INPUT DROP
    
  5. 保存规则

    • 在Debian/Ubuntu上:
      sudo sh -c "iptables-save > /etc/iptables/rules.v4"
      
    • 在CentOS/RHEL上:
      sudo service iptables save
      
  6. 重启防火墙服务(如果需要):

    sudo systemctl restart iptables
    

使用 firewalld

  1. 启动并启用firewalld服务

    sudo systemctl start firewalld
    sudo systemctl enable firewalld
    
  2. 查看当前区域和规则

    sudo firewall-cmd --get-active-zones
    sudo firewall-cmd --list-all
    
  3. 允许特定端口(例如,允许SSH访问):

    sudo firewall-cmd --permanent --add-service=ssh
    
  4. 允许HTTP和HTTPS访问

    sudo firewall-cmd --permanent --add-service=http
    sudo firewall-cmd --permanent --add-service=https
    
  5. 重新加载防火墙配置

    sudo firewall-cmd --reload
    
  6. 查看永久规则

    sudo firewall-cmd --list-all --permanent
    

注意事项

通过以上步骤,你可以在Linux虚拟机中配置防火墙,确保系统的安全性。

0
看了该问题的人还看了