通过SSH获取CPU使用情况

我想通过SSH检索CPU利用率百分比,我试过命令“顶”,但它不会让我。

我正在使用CentOS 6。

我试过这个代码

$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); 

但它每次都给我一个错误:输出:错误:未设置TERM环境variables。

我正在使用PHP。

谢谢大家,但我管理。 我做了这个命令:

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

您可以使用

 top -n 1 mpstat iostat 

一个纯粹的PHP SSH实现phpseclib,有一个漂亮的讨论如何在PHP中做到顶端 :

http://phpseclib.sourceforge.net/ssh/pty.html#top

即。 你需要一个PTY。

 $ssh->enablePTY(); $ssh->exec('top'); $ssh->setTimeout(5); $ansi->appendString($ssh->read()); echo $ansi->getScreen(); 

你也可以用交互模式来做:

 $ansi->appendString($ssh->read('username@username:~$')); $ssh->write("top\n"); $ssh->setTimeout(5); $ansi->appendString($ssh->read()); echo $ansi->getScreen(); 

请注意,输出将具有ANSI转义代码。 下面是ANSI转义代码呈现为HTML格式的例子:

http://phpseclib.sourceforge.net/ssh/examples.html#top