Linux運維基礎之iptables命令詳解

Linux運維基礎之iptables命令詳解

管理員可以使用 iptables 命令配置 Linux 核心防火牆的 IP 資料包過濾規則。從本質上說,iptables 是一種控制網路流量的工具,它能決定哪些資料包可以留下、指向哪裡以及哪些資料包不被允許。

使用 iptables,你可以根據 IP 地址、協議(如 TCP、UDP)、埠或這些的組合來定義過濾器和規則。

因此,在 Linux 中,iptables 通常用於建立、管理和執行有關傳入和傳出網路流量的規則,這有助於完成網路地址轉換(NAT)、資料包過濾和資料包混淆等任務。這使它成為網路安全的重要工具,可以控制在網路的不同點允許或拒絕哪些連線。

下面是一些使用 iptables 命令的方法:

1. 列出規則

要列出防火牆中的所有規則,可以使用 -L 選項。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
iptables -L
iptables -L
iptables -L

2. 阻止一個 IP 地址

要阻止來自特定 IP 地址的所有傳入流量,可以使用 -A 選項將規則附加到鏈中。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
iptables -A INPUT -s 192.168.0.10 -j DROP
iptables -A INPUT -s 192.168.0.10 -j DROP
iptables -A INPUT -s 192.168.0.10 -j DROP

上述命令會阻止來自 IP 地址 192.168.0.10 的所有輸入流量。

3. 允許一個 IP 地址

要允許來自特定 IP 地址的所有傳入流量,可以使用 -A 選項將規則附加到鏈中。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
iptables -A INPUT -s 192.168.0.10 -j ACCEPT
iptables -A INPUT -s 192.168.0.10 -j ACCEPT
iptables -A INPUT -s 192.168.0.10 -j ACCEPT

上述命令允許來自 IP 地址 192.168.0.10 的所有輸入流量。

4. 遮蔽一個埠

要阻止特定埠上的所有傳入流量,可以使用 -A 選項將規則新增到鏈中。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
iptables -A INPUT -p tcp --dport 80 -j DROP
iptables -A INPUT -p tcp --dport 80 -j DROP
iptables -A INPUT -p tcp --dport 80 -j DROP

上述命令會阻止 TCP 80 埠的所有傳入流量。

5. 允許埠

要允許特定埠上的所有傳入流量,可以使用 -A 選項將規則附加到鏈中。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT

上述命令允許所有進入 TCP 80 埠的流量。

6. 刪除規則

要刪除一條規則,可以使用 -D 選項,後面跟上鍊和規則編號。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
iptables -D INPUT 1
iptables -D INPUT 1
iptables -D INPUT 1

上述命令會刪除 INPUT 鏈中的第一條規則。

7. 清除所有規則

要刪除所有規則,可以使用 -F 選項。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
iptables -F
iptables -F
iptables -F

8. 阻止特定服務

如果要阻止特定服務,可以指定服務名稱而不是埠號。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
iptables -A INPUT -p tcp --dport ssh -j DROP
iptables -A INPUT -p tcp --dport ssh -j DROP
iptables -A INPUT -p tcp --dport ssh -j DROP

更多 Linux 命令

目錄操作 rmdir · cd · pwd · exa · ls
檔案操作 cat · cp · dd · less · touch · ln · rename · more · head
檔案系統操作 chown · mkfs · locate
網路 ping · curl · wget · iptables · mtr
搜尋和文字處理 find · grep · sed · whatis · ripgrep · fd · tldr
系統資訊和管理 env · history · top · who · htop · glances · lsof
使用者和會話管理 screen · su · sudo · open

評論留言