1、pip install tabulate
2、代码实现
#!/usr/bin/env python
# -*- coding: utf-8 -*-"""
Windows端口监听程序
显示本机处于监听状态的端口,进程ID和程序名称
"""import subprocess
import re
import os
import sys
from tabulate import tabulatedef get_listening_ports():"""获取所有处于监听状态的端口信息返回包含端口、PID和程序名称的列表"""try:# 使用netstat命令获取所有TCP监听端口netstat_output = subprocess.check_output('netstat -ano -p tcp | findstr "LISTENING"',shell=True, text=True)# 解析netstat输出port_info = []for line in netstat_output.splitlines():# 清理并分割行parts = re.split(r'\s+', line.strip())if len(parts) >= 5:# 提取本地地址和PIDlocal_address = parts[1]pid = parts[4]# 从本地地址中提取端口if ':' in local_address:port = local_address.split(':')[-1]# 获取进程名称try:process_info = subprocess.check_output(f'tasklist /fi "PID eq {pid}" /fo csv /nh',shell=True,text=True)# 解析进程信息if process_info and '","' in process_info:process_name = process_info.split('","')[0].strip('"')port_info.append({'port': port,'pid': pid,'program': process_name})except subprocess.SubprocessError:port_info.append({'port': port,'pid': pid,'program': 'Unknown'})return port_infoexcept subprocess.SubprocessError as e:print(f"获取端口信息时出错: {e}")return []def display_port_info(port_info):"""以表格形式显示端口信息"""if not port_info:print("未找到监听中的端口")return# 准备表格数据table_data = []for info in port_info:table_data.append([info['port'],info['pid'],info['program']])# 按端口号排序table_data.sort(key=lambda x: int(x[0]) if x[0].isdigit() else float('inf'))# 显示表格headers = ["端口", "进程ID", "程序名称"]print(tabulate(table_data, headers=headers, tablefmt="grid"))def main():"""主函数"""print("正在获取本机监听端口信息...\n")port_info = get_listening_ports()display_port_info(port_info)if __name__ == "__main__":try:main()except KeyboardInterrupt:print("\n程序被用户中断")except Exception as e:print(f"程序执行出错: {e}")sys.exit(1)