安装php扩展:
apt-get install libssh2-1-dev libssh2-php
pecl install ssh2-1.0
脚本如下:
$hostuser = "root";
$sshpasswd = "root";
$connection = ssh2_connect('192.168.99.122', "22");
$auth_methods = ssh2_auth_none($connection, $hostuser);
if (in_array('password', $auth_methods)) {
if (ssh2_auth_password($connection, $hostuser, $sshpasswd)) {
$stream = ssh2_exec($connection, 'top -b -n 1 | grep -E "(Cpu\(s\))|(KiB Mem)"');
stream_set_blocking($stream, true);
if ($stream === FALSE) die("command exec failed!");
$rs = stream_get_contents($stream);
} else {
echo "ssh connect failed";
}
} else {
echo "Login failed";
}
$sys_info = explode("\n", $rs);
$cpu_info = explode(",", $sys_info[0]); //CPU占有量 数组
$mem_info = explode(",", $sys_info[1]); //内存占有量 数组
//CPU占有量
$cpu_usage = trim(trim($cpu_info[0], '%Cpu(s): '), 'us'); //百分比
//内存占有量
$mem_total = trim(trim($mem_info[0], 'KiB Mem : '), ' total');
$mem_used = trim(trim($mem_info[2], 'used'));
$mem_usage = round(100 * intval($mem_used) / intval($mem_total), 2); //百分比
//检测时间
$fp = popen("date +\"%Y-%m-%d %H:%M\"", "r");
$rs = fread($fp, 1024);
pclose($fp);
$detection_time = trim($rs);