Skip to content

Instantly share code, notes, and snippets.

@fmerlin
Last active June 10, 2024 20:10
Show Gist options
  • Save fmerlin/d4a60dc4fcdf1687b9742088eb2e4c1c to your computer and use it in GitHub Desktop.
Save fmerlin/d4a60dc4fcdf1687b9742088eb2e4c1c to your computer and use it in GitHub Desktop.
List all the ports opened by processes on the local machine
#!/usr/bin/python
import psutil
"""
List all the ports opened by processes on the local machine
to run it with sudo: sudo python port_processes.py
"""
connections = {}
for c in psutil.net_connections():
if c.status == 'LISTEN':
connections[c.pid] = connections.get(c.pid, set())
connections[c.pid].add(c.laddr[1])
for k, v in connections.iteritems():
p = psutil.Process(k)
print("Process:", p.name(), "Dir:", p.cwd(), "Ports:", list(v))
@INeddHelp
Copy link

how do I list the ports that are being used for each PID?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment