Centos에서 iptables를 구성하는 방법
首先确认CentOS版本,CentOS 6使用iptables默认,CentOS 7/8使用firewalld,默认需安装iptables-services以启用传统iptables;2. 在CentOS 7/8上需停止并禁用firewalld,安装iptables-services后启动并启用iptables服务;3. 使用iptables命令配置规则,包括查看规则、清空规则、设置默认策略、允许回环、已建立连接、SSH、HTTP、HTTPS及ICMP流量;4. 通过service iptables save命令保存规则至/etc/sysconfig/iptables以确保重启后生效;5. 可选使用iptables-restore从文件恢复规则,需确保文件格式正确;6. 可编写脚本自动化配置基本安全规则并保存;7. 操作时需谨慎避免SSH断连,建议通过控制台备份访问方式,频繁验证规则并定期备份配置文件,正确配置后iptables仍为强大可靠的防火墙工具。
Configuring iptables in CentOS depends on the version you're using, as newer versions (CentOS 7 and later) use firewalld
by default instead of directly managing iptables
. However, you can still configure iptables
manually if needed. Below is a guide for both scenarios: using iptables-service
(for traditional iptables) and managing rules directly.

1. Check Your CentOS Version and Default Firewall
First, confirm your CentOS version:
cat /etc/centos-release
- CentOS 6: Uses
iptables
by default. - CentOS 7/8: Uses
firewalld
, butiptables
is still available.
If you want to use classic iptables
instead of firewalld
, disable firewalld
and install iptables-services
.

2. Switch to Iptables (on CentOS 7 or 8)
Stop and disable firewalld:
sudo systemctl stop firewalld sudo systemctl disable firewalld
Install iptables-services:
sudo yum install iptables-services -y
On CentOS 8, use
dnf
instead ofyum
:sudo dnf install iptables-services -y
Start and enable iptables:
sudo systemctl start iptables sudo systemctl enable iptables
Now the system will use traditional iptables
at boot.

3. Basic Iptables Configuration
You can manage rules using the iptables
command. Here are common examples:
View current rules:
sudo iptables -L -n -v
Flush all rules (be careful):
sudo iptables -F
⚠️ Warning: This removes all rules. You may lose SSH access if not careful.
Set default policies:
sudo iptables -P INPUT DROP sudo iptables -P FORWARD DROP sudo iptables -P OUTPUT ACCEPT
This sets a default deny policy on incoming and forwarded traffic.
Allow loopback traffic:
sudo iptables -A INPUT -i lo -j ACCEPT sudo iptables -A OUTPUT -o lo -j ACCEPT
Allow established connections:
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
Allow SSH (port 22):
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
Tip: Change the SSH port first if possible, then adjust the rule accordingly for security.
Allow HTTP and HTTPS:
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
Allow ping (ICMP):
sudo iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
4. Save Iptables Rules
Rules added with iptables
commands are temporary unless saved.
On CentOS 7/8 with iptables-service:
Save rules:
sudo service iptables save
Or:
sudo /usr/libexec/iptables/iptables.init save
This saves rules to /etc/sysconfig/iptables
.
On CentOS 6:
sudo service iptables save
Rules are automatically saved to /etc/sysconfig/iptables
.
5. Restore Rules from File (Optional)
If you have a rules file:
sudo iptables-restore < /etc/sysconfig/iptables
Make sure the format is correct (use iptables-save
to generate it).
6. Example: Basic Secure Iptables Script
Create a script to set up basic rules:
#!/bin/bash # Flush existing rules iptables -F iptables -X # Set default policies iptables -P INPUT DROP iptables -P FORWARD DROP iptables -P OUTPUT ACCEPT # Allow loopback iptables -A INPUT -i lo -j ACCEPT # Allow established connections iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # Allow SSH (change port if needed) iptables -A INPUT -p tcp --dport 22 -j ACCEPT # Allow HTTP/HTTPS iptables -A INPUT -p tcp --dport 80 -j ACCEPT iptables -A INPUT -p tcp --dport 443 -j ACCEPT # Allow ICMP (ping) iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT # Log dropped packets (optional) iptables -A INPUT -j LOG --log-prefix "IPTables-Dropped: " # Save rules service iptables save echo "Firewall configured and saved."
Save it as firewall.sh
, make it executable, and run:
chmod +x firewall.sh sudo ./firewall.sh
Test carefully—especially SSH rules—to avoid lockout.
7. Troubleshooting Tips
- If you get locked out, use the console (via VPS provider) to restore access.
- Always allow SSH before setting
INPUT DROP
. - Use
iptables -L -n -v
frequently to verify rules. - Backup
/etc/sysconfig/iptables
regularly.
Basically, while CentOS 7+ defaults to firewalld
, switching to classic iptables
gives you fine-grained control. Just remember to save your rules and avoid dropping SSH access. With proper care, iptables
remains a powerful and reliable firewall tool.
위 내용은 Centos에서 iptables를 구성하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undress AI Tool
무료로 이미지를 벗다

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Stock Market GPT
더 현명한 결정을 위한 AI 기반 투자 연구

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

충돌을 피하기 위해 기존 버전의 Docker를 제거하고, 2. Yum-Utils를 설치하고 공식 Docker 저장소를 설치하고, 3. Dockerce, CLI 및 Containerd 설치, 4. Docker Services를 시작하고 활성화하여 Hello-World 이미지를 실행하여 설치가 성공했는지 확인하십시오.

먼저 공식 PostgreSQL 저장소를 추가 한 다음 시스템 자체 모듈을 비활성화하고 PostgreSQL 서버 및 클라이언트를 설치하십시오. 데이터베이스를 초기화 한 후 서비스를 시작하고 파워 온 셀프 스타트를 설정하십시오. 그런 다음 인증 방법 및 네트워크 액세스 권한을 구성한 다음 서비스를 다시 시작하여 구성을 적용하도록하십시오.

CHMOD 명령은 CentOS에서 파일 및 디렉토리의 권한을 수정하고 Symbol Mode 및 Digital Mode를 지원하며 읽기, 쓰기 및 실행을 합리적으로 설정하여 시스템 보안을 개선하여 최소 권한의 원칙을 달성 할 수 있습니다.

startByCheckingNetWorkInterfacestatusWitHipAddrShow, ifdown, brysItupUsingIpLinkSetUp.VerifyConnectivityBypingThegateway (findviaiproute | grepdefault) andapublicive likes8.8.8totestlocalandalreachabildy.ifippingsworkb

Cockpitispre-Installedoncentosandcanbeenabledsudosystemctlenable-nowcockpit.socket, stightServiceOnport9090.allowAccessByRunningSudoFiRewAll-cmd- adpermanent- addervice = cockpitandreloadfirewall-cmd-relol.AcseWeTheAtwith-reload

ToConfigUreastAticiPoncentos, editThenetWorkeConfigurationFilein/etc/sysconfig/network-scripts/.first, theinterfaceusingipaddr, thenmodifythecorrespendingifcfcfcfcfcfg-file (예 : ifcfg-ens33) (예 : ifcfg-ens33) wentboot, netboot, onboot, on, ipadmldrd

먼저, CheckInternetAnddnsConnectivityUsingandnsLookup; iffailed, iffailed,/etc/resolv.confwithValiddnsservers.thencleanyumcachewith "yumcleanall",/var/cache/yum 및 RegeeneratemetAdatavia "Yummakecache"

createa2gbswapfileusingddif =/dev/Zeroof =/swapfilebs = 1mcount = 2048.2. WAP/SWAPFILE.4. ENABLEWITHWAPON/SWAPFILE.5.MAKEPERMANENTBYADDING/SWAPFILENONESWAPSWSW00TO/ETC/FSTAB.6.OPTIONALLYSETVM. SUPAPPINES
