-1

I am writing a PHP script that connects to a remove server using SSH. what I need to do is to check if a specific process is running or not so that I can terminate it. I am using the phpseclib. following code connects to the server and lists the processes but i am really stuck in getting the process id of each processes!

include('Net/SSH2.php');
$ssh = new Net_SSH2('192.168.1.1');
$ssh->login('username', 'password') or die("SSH Login failed");
$ps = $ssh->exec('ps -ef | grep ".php"');
echo $ps; 

The output is :

root     32405     1  3 09:45 ?        00:03:30 php /afghanwiz/distributor1.php
root     32407     1  3 09:45 ?        00:03:33 php /afghanwiz/distributor2.php

I have tried to get the pid (here is 32405 and 32407) using exploding the lines and words but no success. Anyone has any idea of such an issue?

M Reza Saberi
  • 7,134
  • 9
  • 47
  • 76

2 Answers2

1

If you know that they are running as root, this might work for you:

$output = <<<EOF
root     32405     1  3 09:45 ?        00:03:30 php /afghanwiz/distributor1.php
root     32407     1  3 09:45 ?        00:03:33 php /afghanwiz/distributor2.php
EOF;

preg_match_all('/root\s+(\d+)/', $output, $m);
var_dump($m[1]);

If the username can be anything, something like:

preg_match_all('/[a-z_][a-z0-9_]{0,30}\s+(\d+)/', $output, $m);

will work. Btw, the username regex was taken from here: https://stackoverflow.com/a/6949914/171318 Thanks!

Community
  • 1
  • 1
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • You are welcome. :) You may also want to know about the `pidof` command. If it is installed on server, you can obtain just the pids as space separated list. – hek2mgl Dec 18 '14 at 11:00
0

You can do something like this, I know its not a very techy solution but it will serve your purpose:

$arr = explode('     ',$ps);
for ($i=1; $i<count($arr); $i=$i+3)
   echo $arr[$i];
Muhammad Bilal
  • 2,106
  • 1
  • 15
  • 24