📜  示例 de script iptables (1)

📅  最后修改于: 2023-12-03 15:11:24.494000             🧑  作者: Mango

示例 de script iptables

什么是iptables?

iptables 是 Linux 系统中用于管理网络连接和安全的工具。它可以在系统级别上管理数据包的流动,如防火墙和网络地址转换 (NAT)。

iptables 统一管理了 IPv4 和 IPv6 数据包过滤功能。每个规则按照顺序依次检查,如果符合规则,则执行相应的操作。可以控制定义 IP、TCP 和 UDP 协议的规则,以及指定动作,如接受、拒绝或重定向。

iptables 的基本语法

iptables 的基本语法如下:

iptables [-t table] command [match] [target/JUMP]

其中:

  • -t 表示要操作的表格,默认为 filter 表;
  • command 表示要执行的动作,如增加规则、删除规则、清空规则等;
  • match 表示要匹配的规则;
  • target/JUMP 表示要执行的动作,如 DROP、ACCEPT、REJECT 等。

关于 iptables 的更多细节,可以查看 iptables 的帮助文档:

$ man iptables
示例 de script iptables

以下是一个示例的 iptables 脚本:

#!/bin/sh

# 清空所有规则
iptables -F
iptables -X
iptables -Z

# 设置默认策略
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# 允许回环接口(loopback)
iptables -A INPUT  -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

# 允许已建立的连接通过
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

# 允许 Ping
iptables -A INPUT -p icmp -m limit --limit 2/minute -j ACCEPT

# 允许 SSH 连接
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# 允许 HTTP 连接
iptables -A INPUT -p tcp --dport 80 -j ACCEPT

# 允许 HTTPS 连接
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# 允许 DNS 查询
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
iptables -A INPUT  -p udp --sport 53 -j ACCEPT

# 允许 NTP 时间同步
iptables -A OUTPUT -p udp --dport 123 -j ACCEPT
iptables -A INPUT  -p udp --sport 123 -j ACCEPT

# 允许 SMTP(邮件发送)
iptables -A OUTPUT -p tcp --dport 25 -j ACCEPT
iptables -A INPUT  -p tcp --sport 25 -j ACCEPT

# 允许 POP3(邮件接收)
iptables -A INPUT -p tcp --dport 110 -j ACCEPT

# 允许 IMAP(邮件接收)
iptables -A INPUT -p tcp --dport 143 -j ACCEPT

# 过滤其余的 ICMP 请求
iptables -A INPUT -p icmp -j REJECT --reject-with icmp-host-unreachable

# 记录被拒绝的请求
iptables -A INPUT -j LOG --log-level 7 --log-prefix "DROP: "

# 保存规则
iptables-save >/etc/sysconfig/iptables

以上脚本开启了一些基本的网络服务,如 SSH、HTTP、HTTPS、DNS、NTP 时间同步等,并且该脚本还能够记录被拒绝的请求,用于监控和调试。

结论

iptables 脚本可以帮助我们在 Linux 系统上管理网络连接和安全。我们可以根据需要定制自己的规则来保护系统的安全,从而在网络上更安全地使用 Linux。