使用netstat和grep与awk定位服务pid
[root@ceshi0 ~]# netstat -tnlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:443 0.0.0.0:* LISTEN 5861/httpd.bin
tcp 0 0 127.0.0.1:8005 0.0.0.0:* LISTEN 17292/java
tcp 0 0 0.0.0.0:8009 0.0.0.0:* LISTEN 17292/java
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 17292/java
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 5861/httpd.bin
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 28705/sshd
tcp6 0 0 :::3306 :::* LISTEN 13572/mysqld
如果是udp协议把u改成t
通过上面的查询结果可以看到pid为17292 开了3个端口
不过当服务过多时很难定位到结果 可以使用grep过滤
[root@ceshi0 ~]# netstat -tnlp|grep 8080
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 17292/java
如果使用脚本的话还可以结合分词获获取pid在结合kill 把服务kill掉
输出地7列
[root@ceshi0 ~]# netstat -tnlp|grep 8080 |awk '{print$7}'
17292/java
只读取端口号
[root@ceshi0 ~]# netstat -tnlp|grep 8080 |awk '{print$7}'| awk -F"/" '{print$1}'
17292
使用kill把找到的pid所对应的进程干掉
[root@ceshi0 ~]# kill -9 17292
[root@ceshi0 ~]# netstat -tnlp|grep 8080 |awk '{print$7}'| awk -F"/" '{print$1}'
[root@ceshi0 ~]# netstat -tnlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:443 0.0.0.0:* LISTEN 5861/httpd.bin
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 5861/httpd.bin
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 28705/sshd
tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN 14885/postgres.bin
tcp6 0 0 :::3306 :::* LISTEN 13572/mysqld
[root@ceshi0 ~]#
可以看到17292所对应的进程被干掉了
下面查询8080端口所对应进程pid同时kill掉
[root@ceshi0 ~]# netstat -tnlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:443 0.0.0.0:* LISTEN 5861/httpd.bin
tcp 0 0 0.0.0.0:8009 0.0.0.0:* LISTEN 19264/java
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 19264/java
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 5861/httpd.bin
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 28705/sshd
tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN 14885/postgres.bin
tcp6 0 0 :::3306 :::* LISTEN 13572/mysqld