系统信息获取util实装

*性能很差,所以...
This commit is contained in:
Chenx221 2024-04-12 16:14:50 +08:00
parent 09df400a94
commit c231a49df7
Signed by: chenx221
GPG Key ID: D7A9EC07024C3021

View File

@ -2,14 +2,19 @@
namespace app\utils; namespace app\utils;
use app\models\CollectionTasks;
use app\models\Share;
use app\models\User;
use DateTime; use DateTime;
use Yii; use Yii;
use yii\db\Exception;
/** /**
* Class SystemInfoHelper * Class SystemInfoHelper
* Get system information * Get system information
* Supported OS: Windows, Linux * Supported OS: Windows, Linux
* Windows needs PowerShell * Windows needs PowerShell
* Linux needs ethtool
*/ */
class SystemInfoHelper class SystemInfoHelper
{ {
@ -26,12 +31,11 @@ class SystemInfoHelper
public string $dataMountPoint; // Data Mount Point public string $dataMountPoint; // Data Mount Point
public string $mp_fs; // Filesystem public string $mp_fs; // Filesystem
public int $mp_size; // Size public int $mp_size; // Size
public string $mp_used; // Used public int $mp_used; // Used
public string $mp_avail; // Available public int $mp_avail; // Available
public string $dns; // DNS public string $dns; // DNS
public string $gateway; // Gateway public string $gateway; // Gateway
public array $nics; // Network Interfaces public array $nic; // Network Interface [interfaceName, mac, speed, ipv4, ipv6]
public array $nicsData; // Network Interfaces Data
public int $users; // Users public int $users; // Users
public int $activeUsers; // Active Users public int $activeUsers; // Active Users
public int $shares; // Shares public int $shares; // Shares
@ -44,43 +48,47 @@ class SystemInfoHelper
public string $extensions; // Extensions public string $extensions; // Extensions
public string $dbType; // Database Type public string $dbType; // Database Type
public string $dbVersion; // Database Version public string $dbVersion; // Database Version
public string $dbSize; // Database Size public int $dbSize; // Database Size
/** /**
* SystemInfoHelper constructor. * 检查操作系统类型
* Detect the OS type before the class is initialized. * 必须在其他检测前调用
* @return void
*/ */
public function __construct() private function detectOsType(): void
{
$this->osType = $this->detectOsType();
}
/**
* @return int
*/
private function detectOsType(): int
{ {
$os = php_uname(); $os = php_uname();
if (stripos($os, 'windows') !== false) { if (stripos($os, 'windows') !== false) {
return 0; $this->osType = 0;
} elseif (stripos($os, 'linux') !== false) { } elseif (stripos($os, 'linux') !== false) {
return 1; $this->osType = 1;
} else { } else {
return 2; $this->osType = 2;
} }
} }
/**
* 获取主机名
* @return void
*/
private function detectHostname(): void private function detectHostname(): void
{ {
$this->hostname = gethostname(); $this->hostname = gethostname();
} }
/**
* 获取操作系统信息
* @return void
*/
private function detectOs(): void private function detectOs(): void
{ {
$this->os = php_uname('s') . ' ' . php_uname('r') . ' ' . php_uname('v') . ' ' . php_uname('m'); $this->os = php_uname('s') . ' ' . php_uname('r') . ' ' . php_uname('v') . ' ' . php_uname('m');
} }
/**
* 获取CPU信息
* @return void
*/
private function detectCpu(): void private function detectCpu(): void
{ {
if ($this->osType === 0) { if ($this->osType === 0) {
@ -94,7 +102,8 @@ class SystemInfoHelper
} }
/** /**
* 32位系统最大只会获取到2147483647结果 * 获取已安装RAM信息
* 32位系统最大只会获取到2147483647结果 (2GB)
* @return void * @return void
*/ */
private function detectRam(): void private function detectRam(): void
@ -106,11 +115,19 @@ class SystemInfoHelper
} }
} }
/**
* 获取服务器时间
* @return void
*/
private function detectServerTime(): void private function detectServerTime(): void
{ {
$this->serverTime = date('Y-m-d H:i:s T'); $this->serverTime = date('Y-m-d H:i:s T');
} }
/**
* 获取服务器已运行时间
* @return void
*/
private function detectServerUptime(): void private function detectServerUptime(): void
{ {
if ($this->osType === 0) { if ($this->osType === 0) {
@ -125,6 +142,7 @@ class SystemInfoHelper
} }
/** /**
* 获取服务器负载
* Only for Linux * Only for Linux
* @return void * @return void
*/ */
@ -133,6 +151,10 @@ class SystemInfoHelper
$this->load = sys_getloadavg()[0]; $this->load = sys_getloadavg()[0];
} }
/**
* 获取CPU使用率
* @return void
*/
private function detectCpuUsage(): void private function detectCpuUsage(): void
{ {
if ($this->osType === 0) { if ($this->osType === 0) {
@ -142,6 +164,10 @@ class SystemInfoHelper
} }
} }
/**
* 获取RAM使用率
* @return void
*/
private function detectRamUsage(): void private function detectRamUsage(): void
{ {
if ($this->osType === 0) { if ($this->osType === 0) {
@ -152,104 +178,204 @@ ngSystem).TotalVisibleMemorySize * 100"')), 2);
} }
} }
/**
* 获取数据挂载点信息
* 包含文件系统、大小、已用、可用
* @return void
*/
private function detectDataMountPoint(): void private function detectDataMountPoint(): void
{ {
$dataPath = Yii::getAlias(Yii::$app->params['dataDirectory']); $dataPath = Yii::getAlias(Yii::$app->params['dataDirectory']);
if ($this->osType === 0) { if ($this->osType === 0) {
$this->dataMountPoint = shell_exec('powershell (Get-Item \"' . $dataPath . '\").PSDrive.Root'); $this->dataMountPoint = shell_exec('powershell (Get-Item \"' . $dataPath . '\").PSDrive.Root'); // X:\
$dmp = substr($this->dataMountPoint, 0, 2); $dmp = substr($this->dataMountPoint, 0, 2); // X:
$this->mp_fs = shell_exec('powershell "(Get-WmiObject Win32_Volume | Where-Object {$_.DriveLetter -eq \'' . $dmp . '\'}).FileSystem"'); $this->mp_fs = shell_exec('powershell "(Get-WmiObject Win32_Volume | Where-Object {$_.DriveLetter -eq \'' . $dmp . '\'}).FileSystem"');
$this->mp_size = shell_exec('powershell "(Get-WmiObject Win32_LogicalDisk | Where-Object {$_.DeviceID -eq \'' . $dmp . '\'}).size"'); $this->mp_size = intval(shell_exec('powershell "(Get-WmiObject Win32_LogicalDisk | Where-Object {$_.DeviceID -eq \'' . $dmp . '\'}).Size"'));
$this->mp_avail = intval(shell_exec('powershell "(Get-WmiObject Win32_LogicalDisk | Where-Object {$_.DeviceID -eq \'' . $dmp . '\'}).FreeSpace"'));
$this->mp_used = $this->mp_size - $this->mp_avail;
} else { } else {
$this->dataMountPoint = shell_exec("df -P \"" . $dataPath . "\" | awk 'NR==2{print $6}'"); $this->dataMountPoint = shell_exec("df -P \"" . $dataPath . "\" | awk 'NR==2{print $6}'");
$this->mp_fs = shell_exec("df -T \"" . $this->dataMountPoint . "\" | awk 'NR==2{print $2}'"); $this->mp_fs = shell_exec("df -T \"" . $this->dataMountPoint . "\" | awk 'NR==2{print $2}'");
$this->mp_size = shell_exec('df -k "' . $this->dataMountPoint . '" | awk \'NR==2{print $2}\''); $this->mp_size = intval(shell_exec('df -k "' . $this->dataMountPoint . '" | awk \'NR==2{print $2}\''));
} $this->mp_used = intval(shell_exec('df -k "' . $this->dataMountPoint . '" | awk \'NR==2{print $3}\''));
} $this->mp_avail = intval(shell_exec('df -k "' . $this->dataMountPoint . '" | awk \'NR==2{print $4}\''));
private function detectMpUsed(): void
{
if ($this->osType === 0) {
} else {
}
}
private function detectMpAvail(): void
{
if ($this->osType === 0) {
} else {
} }
} }
/**
* 获取DNS信息
* @return void
*/
private function detectDns(): void private function detectDns(): void
{ {
if ($this->osType === 0) { if ($this->osType === 0) {
$this->dns = shell_exec('powershell "((Get-NetIPConfiguration | Where-Object { $_.NetAdapter.Status -eq \'Up\' }).DnsServer.ServerAddresses) -join \',\'"');
} else { } else {
$this->dns = shell_exec('cat /etc/resolv.conf | grep nameserver | awk \'{print $2}\' | tr \'\\n\' \',\' | sed \'s/,$//\'');
} }
} }
/**
* 获取网关信息
* @return void
*/
private function detectGateway(): void private function detectGateway(): void
{ {
if ($this->osType === 0) { if ($this->osType === 0) {
$this->gateway = shell_exec('powershell "(Get-NetIPConfiguration | Where-Object { $_.NetAdapter.Status -eq \'Up\' }).IPv4DefaultGateway.NextHop"');
} else { } else {
$this->gateway = shell_exec('ip route | grep default | awk \'{print $3}\'');
} }
} }
private function detectNics(): void /**
* 获取网卡信息
* 包含接口名、MAC地址、速度、IPv4、IPv6
* @return void
*/
private function detectNic(): void
{ {
if ($this->osType === 0) { if ($this->osType === 0) {
$this->nic = [
'interfaceName' => shell_exec('powershell "(Get-NetAdapter | Where-Object { $_.Status -eq \'Up\' }).Name"'),
'mac' => strtolower(shell_exec('powershell "(Get-NetAdapter | Where-Object { $_.Status -eq \'Up\' }).MacAddress"')),
'speed' => shell_exec('powershell "(Get-NetAdapter | Where-Object { $_.Status -eq \'Up\' }).LinkSpeed"'),
'ipv4' => shell_exec('powershell "(Get-NetIPConfiguration | Where-Object { $_.NetAdapter.Status -eq \'Up\' }).IPv4Address.IPAddress"'),
'ipv6' => shell_exec('powershell "(Get-NetIPConfiguration | Where-Object { $_.NetAdapter.Status -eq \'Up\' }).IPv6Address.IPAddress"')
];
} else { } else {
$name = trim(shell_exec('ip link | awk -F: \'$0 !~ "lo|vir|wl|^[^0-9]"{print $2;getline}\''));
$this->nic = [
'interfaceName' => $name,
'mac' => shell_exec("ip addr show $name | awk '/ether/ {print $2}'"),
'speed' => shell_exec("ethtool $name 2>/dev/null | awk '/Speed:/ {print $2}'"),
'ipv4' => shell_exec("ip addr show $name | awk '/inet / {print $2}' | cut -d'/' -f1"),
'ipv6' => shell_exec("ip addr show $name | awk '/inet6 / {print $2}' | cut -d'/' -f1")
];
} }
} }
/**
* 获取用户信息
* 包含用户数、活跃用户数
* @return void
*/
private function detectUsers(): void private function detectUsers(): void
{ {
if ($this->osType === 0) { $this->users = User::find()->count();
$activeTime = date('Y-m-d H:i:s', strtotime('-24 hours'));
} else { $this->activeUsers = User::find()->where(['>', 'last_login', $activeTime])->count();
}
} }
/**
* 获取分享信息
* @return void
*/
private function detectShares(): void private function detectShares(): void
{ {
if ($this->osType === 0) { $this->shares = Share::find()->count();
} else {
}
} }
/**
* 获取收集任务信息
* @return void
*/
private function detectCollections(): void private function detectCollections(): void
{ {
if ($this->osType === 0) { $this->collections = CollectionTasks::find()->count();
} else {
}
} }
/**
* 获取PHP环境信息
* @return void
*/
private function detectEnv(): void private function detectEnv(): void
{ {
if ($this->osType === 0) { $this->phpVersion = phpversion();
$this->memoryLimit = ini_get('memory_limit');
} else { $this->maxExecutionTime = ini_get('max_execution_time');
} $this->uploadMaxFilesize = ini_get('upload_max_filesize');
$this->postMaxSize = ini_get('post_max_size');
$this->extensions = implode(', ', get_loaded_extensions());
} }
/**
* 获取数据库信息
* @return void
*/
private function detectDb(): void private function detectDb(): void
{ {
if ($this->osType === 0) { $this->dbType = Yii::$app->db->driverName;
// debug
} else { // $this->dbVersion = '1';
// $this->dbSize = 1;
// return;
try {
$this->dbVersion = Yii::$app->db->createCommand('SELECT VERSION()')->queryScalar();
} catch (Exception) {
$this->dbVersion = 'Fetch Error';
}
$dbName = $_ENV['DB_NAME'];
try {
$this->dbSize = Yii::$app->db->createCommand("select SUM(data_length + index_length) from information_schema.TABLES where table_schema = '$dbName' group by table_schema;")->queryScalar();
} catch (Exception) {
$this->dbSize = 'Fetch Error';
} }
} }
public static function getSysInfo() /**
* 获取系统信息(初始化)
* @return SystemInfoHelper
*/
public static function getSysInfoInit(): SystemInfoHelper
{ {
$sysInfo = new SystemInfoHelper();
$sysInfo->detectOsType();
$sysInfo->detectHostname();
$sysInfo->detectOs();
$sysInfo->detectCpu();
$sysInfo->detectRam();
$sysInfo->detectServerTime();
$sysInfo->detectServerUptime();
if ($sysInfo->osType === 1) {
$sysInfo->detectLoad();
} else {
$sysInfo->load = -1;
}
$sysInfo->detectCpuUsage();
$sysInfo->detectRamUsage();
$sysInfo->detectDataMountPoint();
$sysInfo->detectDns();
$sysInfo->detectGateway();
$sysInfo->detectNic();
$sysInfo->detectUsers();
$sysInfo->detectShares();
$sysInfo->detectCollections();
$sysInfo->detectEnv();
$sysInfo->detectDb();
return $sysInfo;
} }
/**
* 获取系统信息(刷新)
* 为了减少资源消耗,只刷新部分数据
* @return SystemInfoHelper
*/
public static function getSysInfoFre(): SystemInfoHelper
{
$sysInfo = new SystemInfoHelper();
$sysInfo->detectServerTime();
$sysInfo->detectServerUptime();
if ($sysInfo->osType === 1) {
$sysInfo->detectLoad();
} else {
$sysInfo->load = -1;
}
$sysInfo->detectCpuUsage();
$sysInfo->detectRamUsage();
$sysInfo->detectDataMountPoint();
return $sysInfo;
}
} }