Electron运行环境判断(是否在虚拟机中)

288 阅读1分钟

前言

为了防止用户在虚拟机中运行软件,我们需要为当前运行环境做判断,为虚拟机的话我们退出程序就可以了。

原理:使用命令获取计算机的硬件信息,进行关键字匹配

# win
powershell "Get-WmiObject -Class Win32_ComputerSystem | Select-Object Manufacturer, Model"
# Mac
system_profiler SPHardwareDataType

正文

在主流虚拟机中的情况

  1. Hyper-V

关键字Virtual Machine

img_v3_02pp_8f5fb041-4daa-4c95-87bb-60d6ee3815ag.jpg

  1. VMware

Windows系统,关键字VMware

image.png

Mac系统,关键字Virtual MachineVMware

img_v3_02po_534c98a4-6fc5-4b6a-b50b-3497d6418e2g.jpg

  1. QEMU

关键字QEMU

img_v3_02pp_ca30e874-aaf6-4d15-9fab-14510986453g.jpg

代码

/* 虚拟机特征 */
const vmSignatures = [
  //虚拟机软件
  'VMware',
  //桌面虚拟化软件
  'VirtualBox',
  //开源的桌面虚拟化软件
  'VBox',
  //开源的硬件模拟器和虚拟化器
  'QEMU',
  //开源的虚拟机管理器(或称 hypervisor)
  'Xen',
  //微软开发的硬件虚拟化产品
  'Hyper-V',
  //虚拟化软件
  'Parallels',
  // 关键字
  'Virtual Machine',
];

/* 是否是虚拟机 */
export const isVirtualMachine = async () => {
  if (process.platform == 'win32') {
    return detectWindowsVM(); // 在Windows系统上检测虚拟机
  }
  if (process.platform == 'darwin') {
    return detectMacOSVM(); // 在Mac系统上检测虚拟机
  }
  return false;
};

/* Windows 虚拟机检测 */
const detectWindowsVM = async (): Promise<boolean> => {
  try {
    const { exec } = require('child_process');
    const util = require('util');
    const execAsync = util.promisify(exec);

    // 使用PowerShell Get-WmiObject检查系统制造商
    try {
      const { stdout: systemInfo } = await execAsync(
        'powershell "Get-WmiObject -Class Win32_ComputerSystem | Select-Object Manufacturer, Model"',
      );

      log.info('systemInfo:', systemInfo.toLowerCase());
      for (const signature of vmSignatures) {
        if (systemInfo.toLowerCase().includes(signature.toLowerCase())) {
          log.info('VM detected by Get-WmiObject:', systemInfo);
          return true;
        }
      }
    } catch (error) {
      log.debug('Get-WmiObject check failed:', error);
    }

    return false;
  } catch (error) {
    log.error('Windows VM detection error:', error);
    return false;
  }
};

/* macOS 虚拟机检测 */
const detectMacOSVM = async (): Promise<boolean> => {
  try {
    const { exec } = require('child_process');
    const util = require('util');
    const execAsync = util.promisify(exec);

    // 检查系统硬件信息
    try {
      const { stdout: sysInfo } = await execAsync(
        'system_profiler SPHardwareDataType',
      );

      log.info('macOS system info:', sysInfo.toLowerCase());
      for (const signature of vmSignatures) {
        if (sysInfo.toLowerCase().includes(signature.toLowerCase())) {
          log.info('VM detected by system info:', signature);
          return true;
        }
      }
    } catch (error) {
      log.debug('System info check failed:', error);
    }

    return false;
  } catch (error) {
    log.error('macOS VM detection error:', error);
    return false;
  }
};

结语

感谢阅读