Mini Shell

Direktori : /opt/sharedrads/oldrads/
Upload File :
Current File : //opt/sharedrads/oldrads/check_dstates.py

#!/opt/imh-python/bin/python3
"""Collates and displays useful information on processes in D state"""

import os


def get_uid(pid):
    """Get uid of process"""
    try:
        with open(f'/proc/{pid}/status', encoding='ascii') as file:
            for line in file:
                if line.startswith('Uid:'):
                    return line.split()[1]
    except OSError:
        pass
    return '-'


def get_ctid(pid):
    """Get container associated with PID"""
    try:
        with open(f'/proc/{pid}/stat', encoding='ascii') as file:
            return file.read().split()[-1]
    except OSError:
        return '-'


def main():
    """Grabs the D, jostles it around, and displays it for all to see"""

    iznode = os.path.isdir('/etc/vz/')

    badpids = {}
    for pid in [i for i in os.listdir('/proc') if i.isdigit()]:
        try:
            with open(f'/proc/{pid}/stat', encoding='ascii') as f:
                statinfo = f.read().split()[2]
        except OSError:
            continue

        if 'D' in statinfo:
            badpids[pid] = {'pid': pid}

            try:
                badpids[pid]['exe'] = os.readlink('/proc/%s/exe' % pid)
            except OSError:
                badpids[pid]['exe'] = ''

            badpids[pid]['uid'] = get_uid(pid)

            isnode_output = "%(pid)6s%(uid)6s  %(ctid).4s  %(exe)-60s"
            notnode_output = "%(pid)6s%(uid)6s  %(exe)-60s"
            output_formatter = isnode_output if iznode else notnode_output

            if iznode:
                badpids[pid]['ctid'] = get_ctid(pid)

    print("\n    :: Check Processes in D State ::")

    if iznode:
        print("\n\n%6s%6s  %.4s  %s\n" % ('PID', 'UID', 'CTID', 'Executable'))
    else:
        print("\n\n%6s%6s  %s\n" % ('PID', 'UID', 'Executable'))

    for pid in sorted(badpids, key=lambda x: int(x)):
        print(output_formatter % badpids[pid])
    print('\nTotal: %d\n' % len(badpids))


main()

Zerion Mini Shell 1.0