---
title: "防在终端下配iptables将自己封掉"
author: "itoday"
date: "2010-12-13T22:54:20Z"
tags: []
categories: ["操作系统"]
slug: "iptables"
draft: false
lastmod: "2010-12-13T22:59:34Z"
id: 841276
url: "https://itoday.iteye.com/blog/841276"
---

前几天在用iptables封一些端口；

我的做法是先用netstat查看本机都有开哪些端口，确定端口的使用程序；

然后使用

 

```
]#iptables -P INPUT DROP; iptables -P OUTPUT DROP; iptables -P FORWARD DROP; iptables -A INPUT -p tcp --dport 80 -j ACCEPT; iptables -A OUTPUT -p tcp --sport 80 -j ACCEPT; iptables -A INPUT -p tcp --dport 22 -j ACCEPT; iptables -A OUTPUT -p tcp --sport 22 -j ACCEPT; iptables -A INPUT -p tcp --dport 21 -j ACCEPT; iptables -A OUTPUT -p tcp --sport 21 -j ACCEPT;
```

 

 

这样用

 

```
]#iptables -L -n
```

 

就可以查看防火墙当前规则

 

不过当时忽略了先用nestat查看本机都在使用哪些端口，造成了web中80端口即使开启也无法访问。

 

于是想说先用

 

```
]#iptables -F
```

 

 

清除规则，然后重新查看都有使用哪些端口。

 

结果悲剧来了：iptables中的规则变成了all drop；

                     自己把自己封在外面了；

                     因为服务器是在另外一个城市，不能立刻去改iptables设置，所以服务只能暂时暂停；

 

为此我的总结是：敲回车前要想清楚，确定你知道你在做什么；

                        要认真对待每一个命令；

 

同时，我也写了个shell脚本来防止此类事情再次发生：

 

使用方法就是在你配iptables之前运行

 

```
]#nohup sh iptables-safe.sh > safe.out 2>&1 &
```

   

其实简单的说直接输入

 

```
]#nohup sh iptables-safe.sh &
```

 

这样就好了

 

这个脚本是每60秒检测一次你的终端进程是否在，如果不在，则自动重启；

因此在配置完iptables之后，保存iptables的同时，记得kill 掉这个进程，否则你断开后服务器自动重启可是于我无关。。。

 

iptables-safe.sh在附件中下载