[Golang] 纯文本查看 复制代码
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"log"
"os"
"os/exec"
"strings"
"net"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/disk"
"github.com/shirou/gopsutil/v3/mem"
)
const (
appToken = ""
uid = ""
wxURL = "https://wxpusher.zjiecode.com/api/send/message"
)
func wxPusherSend(msg string) error {
payload := map[string]interface{}{
"appToken": appToken,
"content": msg,
"summary": msg[:min(len(msg), 99)],
"uids": []string{uid},
}
jsonData, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("json marshal failed: %v", err)
}
resp, err := http.Post(wxURL, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
return fmt.Errorf("http post failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad response status: %s", resp.Status)
}
return nil
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// getCpuInfo 使用 wmic 命令获取详细的 CPU 信息。
func getCpuInfo() (string, error) {
cmd := exec.Command("wmic", "cpu", "get", "Name,NumberOfCores,NumberOfLogicalProcessors")
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
return "", fmt.Errorf("命令执行失败: %v, 错误信息: %s", err, stderr.String())
}
lines := strings.Split(out.String(), "\r\n")
var cpuInfoBuilder strings.Builder
for _, line := range lines {
trimmedLine := strings.TrimSpace(line)
if trimmedLine != "" {
cpuInfoBuilder.WriteString(trimmedLine + "\n")
}
}
return strings.TrimSpace(cpuInfoBuilder.String()), nil
}
// getLocalIP 通过连接到外部地址来获取局域网 IP 地址。
func getLocalIP() (string, error) {
conn, err := net.Dial("udp", "223.5.5.5:53") // 使用 DNS 服务器端口 53
if err != nil {
return "", err
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
ip := localAddr.IP.To4()
if ip == nil {
return "", fmt.Errorf("无法获取IPv4地址")
}
return ip.String(), nil
}
func main() {
var msgBuilder strings.Builder
// 获取主机名
hostName, _ := os.Hostname()
msgBuilder.WriteString(fmt.Sprintf("主机名:%s\n", hostName))
// 获取当前用户名
userName := os.Getenv("USERNAME")
msgBuilder.WriteString(fmt.Sprintf("用户名:%s\n", userName))
// 获取局域网IP
ip, err := getLocalIP()
if err != nil {
log.Printf("无法获取局域网IP: %v\n", err)
} else {
msgBuilder.WriteString(fmt.Sprintf("局域网IP:%s\n", ip))
}
// 获取公网IP
publicIPResp, err := http.Get("http://ip-api.com/json")
if err != nil {
msgBuilder.WriteString(fmt.Sprintf("无法获取公网IP地址: %v\n", err))
} else {
defer publicIPResp.Body.Close()
var publicIPResult map[string]interface{}
if err := json.NewDecoder(publicIPResp.Body).Decode(&publicIPResult); err == nil {
if query, ok := publicIPResult["query"].(string); ok {
msgBuilder.WriteString(fmt.Sprintf("公网IP地址:%s\n", query))
} else {
msgBuilder.WriteString("无法解析公网IP地址。\n")
}
} else {
msgBuilder.WriteString(fmt.Sprintf("解析公网IP地址失败: %v\n", err))
}
}
// 获取CPU信息
//cpuInfo, err := cpu.Info()
//if err != nil {
// msgBuilder.WriteString(fmt.Sprintf("无法获取CPU信息: %v\n", err))
// fmt.Printf("无法获取CPU信息: %v\n", err)
//} else if len(cpuInfo) > 0 {
// msgBuilder.WriteString(fmt.Sprintf("CPU名称:%s\n", cpuInfo[0].ModelName))
//} else {
// msgBuilder.WriteString("未找到CPU信息。\n")
//}
// 获取CPU信息(使用 wmic)
cpuInfo, err := getCpuInfo()
if err != nil {
log.Printf("无法获取CPU信息: %v\n", err)
} else {
msgBuilder.WriteString(fmt.Sprintf("CPU信息:\n%s\n", cpuInfo))
}
cpuCount, err := cpu.Counts(true)
if err != nil {
msgBuilder.WriteString(fmt.Sprintf("无法获取CPU个数: %v\n", err))
} else {
msgBuilder.WriteString(fmt.Sprintf("物理CPU个数:%d\n", cpuCount))
}
// 获取内存信息
memInfo, err := mem.VirtualMemory()
if err != nil {
log.Printf("无法获取内存信息: %v\n", err)
} else {
// 手动计算并格式化内存总量和可用内存
totalMemGB := float64(memInfo.Total) / (1024 * 1024 * 1024)
availableMemGB := float64(memInfo.Available) / (1024 * 1024 * 1024)
msgBuilder.WriteString(fmt.Sprintf("内存总量:%.2f GB\n", totalMemGB))
msgBuilder.WriteString(fmt.Sprintf("可用内存:%.2f GB\n", availableMemGB))
}
// 获取硬盘信息
diskPartitions, err := disk.Partitions(true)
if err != nil {
log.Printf("无法获取硬盘分区信息: %v\n", err)
} else {
for _, dp := range diskPartitions {
diskUsage, err := disk.Usage(dp.Mountpoint)
if err != nil {
log.Printf("无法获取磁盘使用情况(%s): %v\n", dp.Device, err)
continue
}
// 手动计算并格式化磁盘大小、已用空间和剩余空间
totalDiskGB := float64(diskUsage.Total) / (1024 * 1024 * 1024)
usedDiskGB := float64(diskUsage.Used) / (1024 * 1024 * 1024)
freeDiskGB := float64(diskUsage.Free) / (1024 * 1024 * 1024)
msgBuilder.WriteString(fmt.Sprintf("盘符:%s\n磁盘大小:%.2f GB\n已用空间:%.2f GB\n剩余空间:%.2f GB\n磁盘使用百分比:%.2f%%\n\n",
dp.Device,
totalDiskGB,
usedDiskGB,
freeDiskGB,
diskUsage.UsedPercent))
}
}
// 发送消息
err = wxPusherSend(msgBuilder.String())
if err != nil {
fmt.Printf("Failed to send message: %v\n", err)
} else {
fmt.Println("Message sent successfully.")
}
}