Enumerate Processes Programmatically In Linux
Using ps
is not necessarily the best way to enumerate running applications programmatically. This is because it will gather additional information that we do not actually need in most cases. The below examples illustrate how to enumerate running applications by reading the contents of /proc
.
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
def get_procs(proc_name=None): ## Loop over /proc and get all Process Data # @param String proc_name The name of the process # @return List process_list A list of active PIDs for the given process current_processes = [] pids = [pid for pid in os.listdir('/proc') if pid.isdigit()] for pid in pids: try: process_name = open('/proc/%s/cmdline' % pid,'rb').read() current_processes.append({ 'Start': int(os.path.getctime('/proc/%s' % pid)), 'Name': process_name.replace('\x00',' ').strip(), 'PID': pid }) except: pass if proc_name: process_list = [] for process in current_processes: if proc_name in process['Name']: process_list.append(process['PID']) return process_list return current_processes |
PHP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
function get_procs( $proc_name=false ){ ## Loop over /proc and get all Process Data # @param String $proc_name The name of the process to look for # @return List process_list A list of active PIDs for the given process, or a list of processes $current_processes = array(); $pids = array(); foreach( scandir('/proc') as $pid ){ if is_numeric( $pid ) array_push( $pids, $pid ); } foreach( $pids as $pid ){ $process_file = sprintf('/proc/%s/cmdline', $pid); if( $process_name = file_get_contents( $process_file ){ $process_data = array( 'Start' => filectime($process_file), 'Name' => str_replace(json_decode("\x00"), ' ', trim($process_name) ), 'PID' => $pid ); array_push($current_processes, $process_data); } } if( $proc_name ){ $process_list = array(); foreach( $current_processes as $process ): if( strpos($process['Name'],$proc_name) === false ) array_push($process_list, $process['PID']); return $process_list } return $current_processes } |