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?
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!