Linux下限制IP访问

来源:互联网 发布:js触发事件 自动 编辑:程序博客网 时间:2024/05/29 18:30

linux下最直接限制ip访问的方式有两种:

1.使用hosts.allow和hosts.deny来设置ip白名单和黑名单,/etc/目录下

 

Java代码  收藏代码
  1. <span style="color: #003366;">优先级为先检查hosts.deny,再检查hosts.allow,   
  2. 后者设定可越过前者限制,   
  3. 例如:   
  4. 1.限制所有的ssh,   
  5. 除非从216.64.87.0 - 127上来。   
  6. hosts.deny:   
  7. in.sshd:ALL   
  8. hosts.allow:   
  9. in.sshd:216.64.87.0/255.255.255.128  
  10.    
  11. 2.封掉216.64.87.0 - 127的telnet   
  12. hosts.deny   
  13. in.sshd:216.64.87.0/255.255.255.128  
  14.    
  15. 3.限制所有人的TCP连接,除非从216.64.87.0 - 127访问   
  16. hosts.deny   
  17. ALL:ALL   
  18. hosts.allow   
  19. ALL:216.64.87.0/255.255.255.128  
  20.    
  21. 4.限制216.64.87.0 - 127对所有服务的访问   
  22. hosts.deny   
  23. ALL:216.64.87.0/255.255.255.128  
  24.    
  25. 其中冒号前面是TCP daemon的服务进程名称,通常系统   
  26. 进程在/etc/inetd.conf中指定,比如in.ftpd,in.telnetd,in.sshd   
  27.    
  28. 其中IP地址范围的写法有若干中,主要的三种是:   
  29. 1.网络地址--子网掩码方式:   
  30. 216.64.87.0/255.255.255.0  
  31. 2.网络地址方式(我自己这样叫,呵呵)   
  32. 216.64.(即以216.64打头的IP地址)   
  33. 3.缩略子网掩码方式,既数一数二进制子网掩码前面有多少个“1”比如:   
  34. 216.64.87.0/255.255.255.0 -- 216.64.87.0/24  
  35.    
  36. 设置好后,要重新启动  
  37. # /etc/rc.d/init.d/xinetd restart  
  38. # /etc/rc.d/init.d/network restart</span>  

 

 2.使用iptables命令

Java代码  收藏代码
  1. <span style="color: #003366;">单个IP的命令是  
  2. iptables -I INPUT -s 81.241.219.171 -j DROP  
  3.    
  4. 封IP段的命令是  
  5. iptables -I INPUT -s 97.47.225.0/16 -j DROP  
  6. iptables -I INPUT -s 97.47.225.0/16 -j DROP  
  7. iptables -I INPUT -s 97.47.225.0/16 -j DROP  
  8.    
  9. 封整个段的命令是  
  10. iptables -I INPUT -s 97.47.225.0/8 -j DROP  
  11.    
  12. 封几个段的命令是  
  13. iptables -I INPUT -s 97.47.225.0/24 -j DROP  
  14. iptables -I INPUT -s 97.47.225.0/24 -j DROP   
  15.    
  16.    
  17. 服务器启动自运行  
  18. 有三个方法:  
  19. 1、把它加到/etc/rc.local中  
  20. 2、vi /etc/sysconfig/iptables可以把你当前的iptables规则放到/etc/sysconfig/iptables中,系统启动iptables时自动执行。  
  21. 3、service   iptables   save 也可以把你当前的iptables规则放/etc/sysconfig/iptables中,系统启动iptables时自动执行。  
  22. 后两种更好些,一般iptables服务会在network服务之前启来,更安全  
  23.    
  24. 解封:  
  25. iptables -L INPUT  
  26. iptables -L --line-numbers 然后iptables -D INPUT 序号   
  27.    
  28.    
  29. iptables 限制ip访问  
  30. 通过iptables限制9889端口的访问(只允许192.168.1.100192.168.1.101192.168.1.102),其他ip都禁止访问  
  31. iptables -I INPUT -p tcp --dport 9889 -j DROP  
  32. iptables -I INPUT -s 192.168.1.100 -p tcp --dport 9889 -j ACCEPT  
  33. iptables -I INPUT -s 192.168.1.101 -p tcp --dport 9889 -j ACCEPT  
  34. iptables -I INPUT -s 192.168.1.102 -p tcp --dport 9889 -j ACCEPT</span>