Search code examples
phplinuxcentos6libssh2

Get CPU usage via SSH


I want to retrieve the CPU utilization percentage via SSH and I have tried the command "top" but it will not let me.

I am using CentOS 6.

I tried this code

$connection = ssh2_connect("IP", PORT);
ssh2_auth_password($connection, "root", "PASS");
$stream = ssh2_exec($connection, "top");
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

// Enable blocking for both streams
stream_set_blocking($errorStream, true);
stream_set_blocking($stream, true);

// Whichever of the two below commands is listed first will receive its appropriate output.  The second command receives nothing
echo "Output: " . stream_get_contents($stream);
echo "Error: " . stream_get_contents($errorStream);

// Close the streams        
fclose($errorStream);
fclose($stream);

But its every time give me an error: Output: Error: TERM environment variable not set.

I'm using PHP.


Solution

  • Thanks everyone but I managed. I did this command:

    top -b -n 10 -d.2 | grep 'Cpu' |  awk 'NR==3{ print($2)}'