Iptables 阻止访问端口8000,除了 IP 地址

我从未使用过 iptables,而且在线文档似乎有点不透明。

我想阻止所有请求端口8000在我的服务器上,除了那些来自一个特定的 IP 地址。如何使用 iptables 实现这一点?

132684 次浏览

This question should be on Server Fault. Nevertheless, the following should do the trick, assuming you're talking about TCP and the IP you want to allow is 1.2.3.4:

iptables -A INPUT -p tcp --dport 8000 -s 1.2.3.4 -j ACCEPT
iptables -A INPUT -p tcp --dport 8000 -j DROP

Another alternative is;

sudo iptables -A INPUT -p tcp --dport 8000 -s ! 1.2.3.4 -j DROP

I had similar issue that 3 bridged virtualmachine just need access eachother with different combination, so I have tested this command and it works well.

Edit**

According to Fernando comment and this link exclamation mark (!) will be placed before than -s parameter:

sudo iptables -A INPUT -p tcp --dport 8000 ! -s 1.2.3.4 -j DROP

You can always use iptables to delete the rules. If you have a lot of rules, just output them using the following command.

iptables-save > myfile

vi to edit them from the commend line. Just use the "dd" to delete the lines you no longer want.

iptables-restore < myfile and you're good to go.

REMEMBER THAT IF YOU DON'T CONFIGURE YOUR OS TO SAVE THE RULES TO A FILE AND THEN LOAD THE FILE DURING THE BOOT THAT YOUR RULES WILL BE LOST.