This commit is contained in:
spiritlhl
2024-05-05 02:02:51 +00:00
parent 632743dfc7
commit feaada0a57
4 changed files with 103 additions and 2 deletions

View File

@@ -1 +1 @@
# basics
# basics

View File

@@ -3,6 +3,8 @@ package system
import (
"context"
"fmt"
"os"
"os/exec"
"runtime"
"time"
@@ -11,6 +13,52 @@ import (
"github.com/shirou/gopsutil/host"
)
func getVmTypeFromSDV(path string) string {
cmd := exec.Command(fmt.Sprintf("%s/systemd-detect-virt", path))
output, err := cmd.Output()
if err == nil {
switch string(output) {
case "kvm":
return "KVM"
case "xen":
return "Xen Hypervisor"
case "microsoft":
return "Microsoft Hyper-V"
case "vmware":
return "VMware"
case "oracle":
return "Oracle VirtualBox"
case "parallels":
return "Parallels"
case "qemu":
return "QEMU"
case "amazon":
return "Amazon Virtualization"
case "docker":
return "Docker"
case "openvz":
return "OpenVZ (Virutozzo)"
case "lxc":
return "LXC"
case "lxc-libvirt":
return "LXC (Based on libvirt)"
case "uml":
return "User-mode Linux"
case "systemd-nspawn":
return "Systemd nspawn"
case "bochs":
return "BOCHS"
case "rkt":
return "RKT"
case "zvm":
return "S390 Z/VM"
case "none":
return "Dedicated"
}
}
return ""
}
func getHostInfo() (string, string, string, string, string, string, string, string, error) {
var Platform, Kernal, Arch, VmType, NatType, CurrentTimeZone string
var cachedBootTime time.Time
@@ -26,7 +74,27 @@ func getHostInfo() (string, string, string, string, string, string, string, stri
Platform = hi.Platform + " " + hi.PlatformVersion
Arch = hi.KernelArch
// 查询虚拟化类型
VmType = hi.VirtualizationSystem
if runtime.GOOS != "windows" {
path, exit := utils.GetPATH("systemd-detect-virt")
if exit {
VmType = getVmTypeFromSDV(path)
}
if VmType == "" {
_, err := os.Stat("/.dockerenv")
if os.IsExist(err) {
VmType = "Docker"
}
_, err = os.Stat("/dev/lxss")
if os.IsExist(err) {
VmType = "Windows Subsystem for Linux"
}
if VmType == "" {
VmType = "Dedicated (No visible signage)"
}
}
} else {
VmType = hi.VirtualizationSystem
}
// 系统运行时长查询
cachedBootTime = time.Unix(int64(hi.BootTime), 0)
}

View File

@@ -2,6 +2,7 @@ package utils
import (
"bytes"
"os"
"os/exec"
"strings"
)
@@ -68,3 +69,30 @@ func GetTimeZone() string {
}
return CurrentTimeZone
}
// GetPATH 检测本机的PATH环境是否含有对应的命令
func GetPATH(key string) (string,bool) {
// 指定要搜索的目录列表
dirs := []string{"/usr/local/bin", "/usr/local/sbin", "/usr/bin", "/usr/sbin", "/sbin", "/bin", "/snap/bin"}
// 循环遍历每个目录
for _, dir := range dirs {
// 检查目录是否存在
_, err := os.Stat(dir)
if os.IsNotExist(err) {
continue
}
cmd := exec.Command("ls", dir)
output, err := cmd.Output()
if err != nil {
continue
}
files := strings.Split(string(output), "\n")
for _, file := range files {
if file == key {
return dir, true
}
}
}
return "", false
}

View File

@@ -130,3 +130,8 @@ func GetTimeZone() string {
return ""
}
}
// GetPATH 检测本机的PATH环境是否含有对应的命令
func GetPATH(key string) (string, bool) {
return "", false
}