你可以使用Python的subprocess
模块来运行shell命令,然后解析输出结果。这里是一个例子:
import subprocess
def get_active_ports():
# Run the 'netstat' command to get active ports
command = "sudo netstat -tuln"
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
# If there was an error, print it and return
if error:
print(f"Error: {error}")
return
# Split the output into lines
lines = output.decode().split("\n")
# The first two lines are headers, so ignore them
lines = lines[2:]
# Parse each line
for line in lines:
# Ignore empty lines
if not line:
continue
# Split the line into parts
parts = line.split()
# The fourth part is the address and port
address, port = parts[3].rsplit(":", 1)
# The sixth part is the process ID and name
process_info = parts[6] if len(parts) > 6 else "N/A"
# Print the information
print(f"Address: {address}, Port: {port}, Process: {process_info}")
get_active_ports()
注意,这段代码需要在具有sudo权限的环境中运行,因为netstat -tuln
命令需要sudo权限。如果你不希望使用sudo,你可以尝试使用ss -tuln
命令,但是这个命令可能无法提供进程信息。
此外,这段代码假设输出的格式是固定的,如果实际的输出格式与这个假设不符,可能需要调整代码。