怎么用脚本获取系统运行时长

wen 实用脚本 3

本文目录导读:

怎么用脚本获取系统运行时长

  1. Windows (PowerShell)
  2. Linux/Unix (Bash)
  3. macOS (Bash)
  4. Python (跨平台)
  5. Node.js (JavaScript)
  6. 批处理 (Windows CMD)
  7. 推荐方案

Windows (PowerShell)

# 方法1:使用 Get-CimInstance
$uptime = (Get-Date) - (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime
Write-Host "系统已运行: $($uptime.Days) 天 $($uptime.Hours) 小时 $($uptime.Minutes) 分钟"
# 方法2:使用 systeminfo
$bootTime = (systeminfo | Select-String "系统启动时间:").ToString().Split(':')[1].Trim()
$uptime = (Get-Date) - [DateTime]$bootTime
Write-Host "系统已运行: $($uptime.Days) 天 $($uptime.Hours) 小时"

Linux/Unix (Bash)

#!/bin/bash
# 方法1:使用 uptime 命令
uptime -p
# 方法2:从 /proc/uptime 获取秒数
uptime_seconds=$(cat /proc/uptime | awk '{print $1}')
uptime_seconds=${uptime_seconds%.*}  # 去除小数部分
days=$((uptime_seconds / 86400))
hours=$(( (uptime_seconds % 86400) / 3600 ))
minutes=$(( (uptime_seconds % 3600) / 60 ))
seconds=$((uptime_seconds % 60))
echo "系统已运行: ${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒"
# 方法3:使用 who -b 获取启动时间
boot_time=$(who -b | awk '{print $3, $4}')
echo "系统启动时间: $boot_time"

macOS (Bash)

#!/bin/bash
# macOS 使用类似 Linux 的方法
uptime_seconds=$(sysctl -n kern.boottime | awk '{print $4}' | sed 's/,//')
current_time=$(date +%s)
uptime=$((current_time - uptime_seconds))
days=$((uptime / 86400))
hours=$(( (uptime % 86400) / 3600 ))
minutes=$(( (uptime % 3600) / 60 ))
echo "系统已运行: ${days}天 ${hours}小时 ${minutes}分钟"

Python (跨平台)

import platform
import time
import psutil  # 需要安装: pip install psutil
def get_system_uptime():
    system = platform.system()
    if system in ["Linux", "macOS"]:
        # Unix/Linux/Mac 方法
        with open('/proc/uptime', 'r') as f:
            uptime_seconds = float(f.readline().split()[0])
    elif system == "Windows":
        # Windows 方法
        import ctypes
        lib = ctypes.windll.kernel32
        uptime_ms = lib.GetTickCount64()
        uptime_seconds = uptime_ms / 1000.0
    else:
        raise Exception("不支持的操作系统")
    return uptime_seconds
# 使用 psutil (跨平台,推荐)
def get_uptime_psutil():
    import psutil
    uptime_seconds = time.time() - psutil.boot_time()
    return uptime_seconds
# 格式化输出
def format_uptime(seconds):
    days = int(seconds // 86400)
    hours = int((seconds % 86400) // 3600)
    minutes = int((seconds % 3600) // 60)
    secs = int(seconds % 60)
    return f"{days}天 {hours:02d}小时 {minutes:02d}分钟 {secs:02d}秒"
# 使用示例
uptime = get_system_uptime()
print(f"系统运行时长: {format_uptime(uptime)}")
# 或使用 psutil
uptime2 = get_uptime_psutil()
print(f"系统运行时长(psutil): {format_uptime(uptime2)}")

Node.js (JavaScript)

// 安装依赖: npm install systeminformation
const si = require('systeminformation');
async function getUptime() {
    try {
        const timeData = await si.time();
        const seconds = timeData.uptime;
        const days = Math.floor(seconds / 86400);
        const hours = Math.floor((seconds % 86400) / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        console.log(`系统已运行: ${days}天 ${hours}小时 ${minutes}分钟`);
        return { days, hours, minutes, seconds };
    } catch (error) {
        console.error('获取系统运行时长失败:', error);
    }
}
getUptime();

批处理 (Windows CMD)

@echo off
:: 方法1:使用 net statistics
for /f "skip=8 tokens=2 delims=: " %%a in ('net statistics workstation') do (
    if not defined boot_time set boot_time=%%a
)
echo 系统启动时间: %boot_time%
:: 方法2:使用 wmic
for /f "skip=1 tokens=*" %%a in ('wmic os get lastbootuptime') do (
    set boot_time=%%a
    goto :parse
)
:parse
echo 系统启动时间: %boot_time%

推荐方案

  • Windows:使用 PowerShell 的 Get-CimInstance 方法
  • Linux/Unix:使用 /proc/uptimeuptime 命令
  • 跨平台脚本:使用 Python 的 psutil 库,简单且兼容性好

选择适合你操作系统和使用场景的方法即可。

抱歉,评论功能暂时关闭!