溫馨提示×

Linux防火墻如何限制外部訪問

小樊
46
2025-09-27 09:18:03
欄目: 智能運維

在Linux系統中,可以使用iptables或firewalld來限制外部訪問。這里分別介紹這兩種方法:

  1. 使用iptables限制外部訪問:

iptables是Linux系統中的一個命令行工具,用于配置內核防火墻。以下是一些基本的iptables規則,用于限制外部訪問:

  • 阻止所有外部訪問:
sudo iptables -P INPUT DROP
  • 允許已建立的連接和相關的數據包通過:
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
  • 允許SSH訪問(假設SSH端口為22):
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
  • 允許HTTP和HTTPS訪問(假設HTTP端口為80,HTTPS端口為443):
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
  • 保存iptables規則:
sudo iptables-save > /etc/iptables/rules.v4

注意:iptables規則在系統重啟后可能會丟失。要使規則永久生效,可以考慮使用iptables-persistent或其他第三方工具。

  1. 使用firewalld限制外部訪問:

firewalld是另一個用于配置Linux防火墻的命令行工具。以下是一些基本的firewalld規則,用于限制外部訪問:

  • 阻止所有外部訪問:
sudo firewall-cmd --set-default-zone=drop
  • 允許已建立的連接和相關的數據包通過:
sudo firewall-cmd --permanent --zone=trusted --add-interface=lo
  • 允許SSH訪問(假設SSH端口為22):
sudo firewall-cmd --permanent --zone=public --add-service=ssh
  • 允許HTTP和HTTPS訪問(假設HTTP端口為80,HTTPS端口為443):
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
  • 重新加載firewalld配置:
sudo firewall-cmd --reload

注意:firewalld規則在系統重啟后仍然有效。如果需要刪除或修改規則,可以使用firewall-cmd命令。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女