如何确定哪个进程正在使用 Linux 中的端口

How to determine which process is using a port in Linux

我目前 运行 RethinkDB 在其默认端口上,因为如果我将浏览器指向 localhost:8080 我会看到 RethinkDB 网络界面:

我想关闭 RethinkDB,然后使用 --port-offset 参数在另一个端口上重新打开它。但是,到目前为止,我无法使用 conn.close() 方法从 Python 中关闭它。

相反,我想通过简单地终止使用该端口的进程来尝试一种蛮力方法。我试图通过使用 netstat 来确定哪个进程,但没有显示任何结果:

kurt@kurt-ThinkPad:~$ netstat -a | grep 8080
kurt@kurt-ThinkPad:~$ 

如何终止 RethinkDB 进程以使端口再次可用?

1.  lsof -i:8080
2.  kill $(lsof -t -i:8080)
or
2 . kill -9 $(lsof -t -i:8080)

根据Klaus D.的评论,我确定了使用netstat -nlp的过程:

kurt@kurt-ThinkPad:~$ netstat -nlp | grep 8080
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        0      0 127.0.1.1:8080          0.0.0.0:*               LISTEN      2229/rethinkdb  
tcp        0      0 127.0.0.1:8080          0.0.0.0:*               LISTEN      2229/rethinkdb  
tcp6       0      0 ::1:8080                :::*                    LISTEN      2229/rethinkdb 

参数代表

  • numeric(显示数字地址而不是尝试确定符号主机、端口或用户名)
  • listening(仅显示监听套接字(默认省略))
  • program(显示每个套接字所属程序的PID和名称)

分别

很棒的回答@codespy。 我做了一个bash文件,然后这样写的。

!/bin/bash

杀死 $(lsof -t -i :8000)

并保存它和脚本文件。

并通过 $chmod +x script_filename

现在我 运行 只需输入 ./script_filename

找出被指控的特定端口的 pid 或所有信息

sudo lsof -i :PORT_NUMBER

终止进程或事件

kill -9 PID

示例:-

harshit@harshit:~/Desktop/edwin-diaz/cms$ lsof -i :4111
COMMAND  PID    USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
node    9215 harshit   33u  IPv6 297470      0t0  TCP *:4111 (LISTEN)
harshit@harshit:~/Desktop/edwin-diaz/cms$ kill -9 9215

有一个简单的解决方案,有些Unix/Linus有命令ss,这是类似于netstat的新一代命令,您只需键入以下内容:

ss -ltnp

-p 列出进程号

-l 列出侦听套接字

-t 列出 tcp 套接字

-n 列出端口号而不是常规名称(21 而不是 ssh)

查看手册页了解更多信息