Skip to content

Instantly share code, notes, and snippets.

@AfroThundr3007730
Created June 23, 2019 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AfroThundr3007730/f8e8418277dbbe1270c79f27894b6515 to your computer and use it in GitHub Desktop.
Save AfroThundr3007730/f8e8418277dbbe1270c79f27894b6515 to your computer and use it in GitHub Desktop.
Parses process statistics from /proc into JSON for a given PID
#!/usr/bin/python3
import os
import sys
import json
def parse_proc():
values = {}
PID = sys.argv[1] if len(sys.argv) > 1 else os.getpid()
values['PID'] = PID
with open(os.path.join('/proc', str(PID), 'cmdline'), 'r') as f:
cmdline = f.read()[:-1].replace('\0', ' ')
values['cmdline'] = cmdline
with open(os.path.join('/proc', str(PID), 'net/netstat'), 'r') as f:
netstat = f.read().split('\n')[:-1]
values['netstat'] = {}
for i in range(0, len(netstat), 2):
key = netstat[i].split(':')[0]
values['netstat'][key] = dict(zip(netstat[i].split(' ')[1:],
netstat[i+1].split(' ')[1:]))
with open(os.path.join('/proc', str(PID), 'status'), 'r') as f:
status = f.read().split('\n')[:-1]
values['status'] = {}
for i in range(0, len(status)):
key, val = status[i].split(':')
values['status'][key] = val.replace('\t', ' ').lstrip()
with open(os.path.join(os.getcwd(),
'pid_' + str(PID) + '_procinfo.json'), 'w') as f:
json.dump(values, f, indent=4, sort_keys=True)
if __name__ == '__main__':
parse_proc()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment