iptables 基操(基本操做)

經常使用命令

  1. 清空當前的全部規則和計數
iptables -F  #清空全部的防火牆規則
iptables -X  #刪除用戶自定義的空鏈
iptables -Z #清空計數
複製代碼
  1. 配置容許ssh端口鏈接
iptables -A INPUT -s 192.168.1.0/24 -p tcp --dport 22 -j ACCEPT  #22爲你的ssh端口, -s 192.168.1.0/24表示容許這個網段的機器來鏈接,其它網段的ip地址是登錄不了你的機器的。 -j ACCEPT表示接受這樣的請求
複製代碼
  1. 容許本地迴環地址能夠正常使用
iptables -A INPUT -i lo -j ACCEPT  #本地圓環地址就是那個127.0.0.1,是本機上使用的,它進與出都設置爲容許
iptables -A OUTPUT -o lo -j ACCEPT
複製代碼
  1. 設置默認規格
iptables -P INPUT DROP #配置默認的不讓進
iptables -P FORWARD DROP #默認的不容許轉發
iptables -P OUTPUT ACCEPT #默認的能夠出去
複製代碼
  1. 配置白名單
iptables -A INPUT -p all -s 192.168.1.0/24 -j ACCEPT  #容許機房內網機器能夠訪問
iptables -A INPUT -p all -s 192.168.140.0/24 -j ACCEPT  #容許機房內網機器能夠訪問
iptables -A INPUT -p tcp -s 183.121.3.7 --dport 3380 -j ACCEPT #容許183.121.3.7訪問本機的3380端口
複製代碼
  1. 開啓相應的服務端口
iptables -A INPUT -p tcp --dport 80 -j ACCEPT #開啓80端口,由於web對外都是這個端口
iptables -A INPUT -p icmp --icmp-type 8 -j ACCEPT #容許被ping
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT #已經創建的鏈接得讓它進來
複製代碼
  1. 保存規則
[root@zejin238 ~]# cp /etc/sysconfig/iptables /etc/sysconfig/iptables.bak #任何改動以前先備份,請保持這一優秀的習慣
[root@zejin238 ~]# iptables-save > /etc/sysconfig/iptables 
[root@zejin238 ~]# cat /etc/sysconfig/iptables
# Generated by iptables-save v1.4.7 on Wed Sep 28 18:06:07 2016
*filter
:INPUT DROP [8:632]  
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [4:416]
-A INPUT -s 192.168.1.0/24 -p tcp -m tcp --dport 22 -j ACCEPT 
-A INPUT -i lo -j ACCEPT 
-A INPUT -s 192.168.1.0/24 -j ACCEPT 
-A INPUT -s 192.168.140.0/24 -j ACCEPT 
-A INPUT -s 183.121.3.7/32 -p tcp -m tcp --dport 3380 -j ACCEPT 
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT 
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT 
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT 
-A OUTPUT -o lo -j ACCEPT 
COMMIT
# Completed on Wed Sep 28 18:06:07 2016
複製代碼

理解iptables格式

咱們在上面的iptables文件中,最開始接觸會發現格式蠻奇怪的,不知道什麼回事web

其實iptables就是定義一些規則,知足相應的規則則進行ACCEPT、DROP、REJECT、DNAT、SNAT......bash

那麼怎麼定義匹配規則:ssh

通用匹配tcp

-s 指定源地址spa

-d 指定目標地址code

-p 指定協議接口

-i 指定數據報文流入接口ip

-o 指定數據報文流出接口io

擴展匹配table

指定-m選項,表示用什麼模塊來匹配,如:

-m state --state

NEW,ESTABLISHED,RELATED  表示用state模塊來匹配當前鏈接狀態爲這三種狀態的鏈接
複製代碼

-m iprange

--src-range 用iprange模塊匹配來源的ip地址範圍

   --dst-range 用iprange模塊匹配目的的ip地址範圍
複製代碼

-m multiport

--source-ports  用multiport模塊來匹配來源的端口範圍

    --destination-ports 用multiport模塊來匹配目的的端口範圍
複製代碼

咱們看以下一條例子來解讀:

-A INPUT -p tcp -m iprange --src-range 121.21.30.36-121.21.30.100 -m multiport --destination-ports 3326,3327,3328 -m state --state NEW -j ACCEPT

這表示來自121.21.30.36-121.21.30.100這個地址範圍的,請求端口爲3326,3327,3328而且是新建的鏈接,都給予放行。

相關文章
相關標籤/搜索