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:**
{{{ lang=python line=1
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:**
{{{ lang=php line=1
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
}
}}}


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *