使用Python检查端口占用情况

使用adb的时候,有时候会发现5037端口被其他程序占用了。于是有了以下这个脚本,检查端口被占用的情况,并结束该进程。

开发环境:Python3.5+Win10+Pycharm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
import os
def is_port_used(port=5037, kill=False):
cmd = 'netstat -ano | findstr {} | findstr LISTENING'.format(port)
print(cmd)
result = os.popen(cmd).read()
print(result)
pid = None
if result != '':
try:
pid = result.split()[-1]
result = os.popen('tasklist /FI "PID eq {0}'.format(pid)).read()
""":type: str """
print(result)
position = result.rfind('=====')
program_name = result[position + 5:].split()[0]
print("占用的程序是{}".format(program_name))
result = os.popen('wmic process where name="{0}" get executablepath'.format(program_name)).read()
result = result.split()
print("占用的程序所在位置:{}".format(result[1]))
cmd = "explorer {0}".format(os.path.dirname(result[1]))
execute_cmd(cmd) # 打开所在文件夹
except Exception:
import traceback
traceback.print_exc()
finally:
if kill:
if not pid:
raise Exception("pid is None")
print(os.popen("taskkill /F /PID {0}".format(pid)).read()) # 结束进程
else:
print('{}端口没有被占用'.format(port))
if __name__ == '__main__':
is_port_used()
input()

运行结果:

1
2
3
4
5
6
7
8
9
10
netstat -ano | findstr 5037 | findstr LISTENING
TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 16600
映像名称 PID 会话名 会话# 内存使用
========================= ======== ================ =========== ============
adb.exe 16600 Console 1 3,868 K
占用的程序是adb.exe
占用的程序所在位置:C:\Android\sdk\platform-tools\adb.exe