netstat是最常用的端口占用查询方式,安装方法如下

sudo yum -y install net-tools
sudo apt install net-tools
sudo pacman -S net-tools

打印目前所有监听中的服务,-t显示所有tcp服务,-u显示所有udp服务,-l显示所有sockets服务,-n禁用反向域名解析,-p显示进程PID

➜  ~ sudo netstat -tulpn
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 127.0.0.1:8384          0.0.0.0:*               LISTEN      817/syncthing       
...
udp6       0      0 :::35676                :::*                                817/syncthing       
udp6       0      0 :::5353                 :::*                                551/avahi-daemon: r

通常搭配grep查找具体程序

sudo netstat -tulpn | grep syncthing #查找名为syncthing的程序
sudo netstat -tulpn | grep 8384 #查找端口8384的占用进程

ss命令与netstat命令一致

sudo ss -tulpn | grep syncthing #查找名为syncthing的程序
sudo ss -tulpn | grep 8384 #查找端口8384的占用进程

lsof是Linux中用于查看打开文件的命令行程序,也可以用于查看端口占用情况

安装方法如下

sudo yum -y install lsof
sudo apt install lsof
sudo pacman -S lsof

查找端口方法如下

sudo lsof -i :8384

ffuserlsof类似,也是用于报告进程所使用的文件资源

安装方法如下

sudo yum -y install psmisc
sudo apt install psmisc
sudo pacman -S psmisc 

查找端口方法如下

sudo fuser -v 8384/tcp

4种方法探查结果如下

➜  ~ sudo netstat -tulpn | grep 8384     
tcp        0      0 127.0.0.1:8384          0.0.0.0:*               LISTEN      817/syncthing       


➜  ~ sudo ss -tulpn | grep syncthing
udp   UNCONN 0      0                                 0.0.0.0:21027      0.0.0.0:*    users:(("syncthing",pid=817,fd=15))        
udp   UNCONN 0      0                                 0.0.0.0:36269      0.0.0.0:*    users:(("syncthing",pid=817,fd=14))        
udp   UNCONN 0      0                                    [::]:21027         [::]:*    users:(("syncthing",pid=817,fd=21))        
udp   UNCONN 0      0                                       *:22000            *:*    users:(("syncthing",pid=817,fd=13))        
udp   UNCONN 0      0                                    [::]:35676         [::]:*    users:(("syncthing",pid=817,fd=16))        
tcp   LISTEN 0      4096                            127.0.0.1:8384       0.0.0.0:*    users:(("syncthing",pid=817,fd=24))        
tcp   LISTEN 0      4096                                    *:22000            *:*    users:(("syncthing",pid=817,fd=12))        


➜  ~ sudo lsof -i :8384
COMMAND   PID    USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
syncthing 817 chancel   24u  IPv4  16076      0t0  TCP localhost:8384 (LISTEN)


➜  ~ sudo fuser -v 8384/tcp
                     USER        PID ACCESS COMMAND
8384/tcp:            chancel     817 F.... syncthing

参考资料