查看服务器上开放的端口(适用于 Linux 和 Windows 服务器):
一、本地查看(在服务器上执行命令)
1. Linux 系统
-
netstat
命令(经典工具):netstat -tuln
-t
:TCP 端口-u
:UDP 端口-l
:仅显示监听中的端口-n
:以数字形式显示端口(不解析服务名)
-
ss
命令(更现代,推荐):ss -tuln
- 参数同
netstat
,速度更快。
- 参数同
-
lsof
命令(查看进程占用的端口):lsof -i -P -n | grep LISTEN
-i
:显示网络连接-P
:禁用端口别名(显示数字端口)-n
:禁用主机名解析(显示 IP)
2. Windows 系统
netstat
命令:netstat -ano | findstr "LISTENING"
-a
:所有连接和监听端口-n
:以数字形式显示-o
:显示进程 PID- 用
Tasklist | findstr "PID"
查看对应进程名。
二、远程扫描(从其他机器扫描服务器)
使用 nmap
工具(需安装):
nmap -sT -p- 服务器IP
-sT
:TCP 连接扫描(最常用)-p-
:扫描所有端口(1-65535)- 精简扫描:
nmap -sT 服务器IP
(仅扫描常见端口)
✅ 示例:
nmap -sT 192.168.1.100
三、检查防火墙规则
- Linux(iptables):
iptables -L -n -v # 查看开放规则
- Linux(firewalld):
firewall-cmd --list-all
- Windows:
Get-NetFirewallRule | Where-Object { $_.Enabled -eq 'True' } # PowerShell
注意事项
- 权限问题:
- Linux 需要
sudo
执行部分命令(如lsof
)。
- Linux 需要
- 防火墙干扰:
- 服务器本地可能开放端口,但防火墙可能阻止外部访问。
- 安全风险:
- 非必要端口(如 MySQL 的 3306、Redis 的 6379)不应暴露到公网,用防火墙/IP白名单限制访问。
排查步骤建议
- 在服务器本地用
ss -tuln
确认端口是否监听。 - 检查防火墙是否允许该端口(云服务器需检查安全组)。
- 从外部使用
nmap
扫描验证是否可达。