import os
import shutil
import socket
import subprocess

s = socket.socket()
s.bind(("127.0.0.1", 0))
s.listen(1)
pid = os.getpid()
port = s.getsockname()[1]
commands = [
 ["ps", "-p", str(pid), "-o", "pid,ppid,stat,pcpu,pmem,rss,vsz,comm"],
 ["top", "-b", "-n", "1", "-p", str(pid)],
 ["ss", "-ltn", f"sport = :{port}"],
 ["lsof", "-nP", "-a", "-p", str(pid), "-iTCP"],
]
try:
 for cmd in commands:
  print("$ " + " ".join(cmd), flush=True)
  if shutil.which(cmd[0]) is None:
   print("unavailable", flush=True)
   continue
  result = subprocess.run(cmd, text=True, stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT, timeout=10)
  print(result.stdout, end="", flush=True)
  print(f"exit={result.returncode}", flush=True)
finally:
 s.close()
