为何firewall-cmd无法列出本地活跃端口?如何使其显示与nmap一致的端口?
Hey there! Let's clear up the confusion first—firewall-cmd and nmap serve totally different purposes, which is why their output doesn't match by default. Let's break this down step by step to get you the info you need.
Why the Mismatch?
nmap(when run locally) scans all listening ports on your system, regardless of firewall rules. It’s checking what services are actually running and waiting for connections.firewall-cmdby default shows ports/services that the firewall allows incoming traffic to. It doesn’t report on active listening ports unless you explicitly cross-reference it with system network tools.
1. How to List Active Listening Ports (Like Nmap Does)
If your goal is to see all local active ports (same as running nmap localhost), firewall-cmd isn’t the right tool for this job. Use these dedicated network utilities instead:
- Run
ss -tuln(the modern alternative to netstat) to list all TCP/UDP listening ports:ss -tuln - Or the older
netstat(if it’s installed on your system):netstat -tuln
Both commands will show you exactly which ports are being listened on, just like a local Nmap scan.
2. Fix Empty firewall-cmd Output & List Allowed Ports
If you ran firewall-cmd and got no results, that means no ports or services are currently open in your firewall rules. Here’s how to fix that:
- First, confirm your current allowed ports/services (this is probably what you ran before):
firewall-cmd --list-ports firewall-cmd --list-services - If output is empty, add the ports or services you want to allow. For example:
- Allow TCP port 80:
firewall-cmd --add-port=80/tcp --permanent - Allow the HTTP service (which maps to port 80):
firewall-cmd --add-service=http --permanent
- Allow TCP port 80:
- After adding rules, reload the firewall to apply changes:
firewall-cmd --reload - Run
--list-portsagain, and you’ll see the allowed ports listed clearly.
3. Cross-Reference Listening Ports with Firewall Rules
If you want to see which active listening ports are actually allowed by the firewall (combining Nmap-like data with firewall rules), use this handy one-liner:
ss -tuln | awk '{print $5}' | grep -E ':[0-9]+$' | cut -d: -f2 | sort | uniq | while read port; do if firewall-cmd --query-port="$port/tcp" || firewall-cmd --query-port="$port/udp"; then echo "Port $port is listening AND allowed by firewall" else echo "Port $port is listening but NOT allowed by firewall" fi done
This script checks each listening port against your firewall rules and tells you exactly which ones are open to incoming traffic.
内容的提问来源于stack exchange,提问作者scrapy

