如何编写软件版本检测脚本

wen 实用脚本 23

本文目录导读:

如何编写软件版本检测脚本

  1. Shell脚本检测系统软件版本
  2. Python版本检测脚本
  3. PowerShell版本检测脚本 (Windows)
  4. 版本比较工具函数
  5. 自动化版本检查和使用建议
  6. 使用建议

Shell脚本检测系统软件版本

#!/bin/bash
# 检查Python版本
check_python() {
    if command -v python3 &> /dev/null; then
        python_version=$(python3 --version 2>&1 | awk '{print $2}')
        echo "Python版本: $python_version"
    elif command -v python &> /dev/null; then
        python_version=$(python --version 2>&1 | awk '{print $2}')
        echo "Python版本: $python_version"
    else
        echo "Python未安装"
    fi
}
# 检查Node.js版本
check_node() {
    if command -v node &> /dev/null; then
        node_version=$(node --version 2>&1 | sed 's/v//')
        echo "Node.js版本: $node_version"
    else
        echo "Node.js未安装"
    fi
}
# 检查多个软件版本
check_all_versions() {
    echo "=== 软件版本检测 ==="
    # 检查操作系统
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        echo "操作系统: $NAME $VERSION"
    fi
    check_python
    check_node
    # 检查Git
    if command -v git &> /dev/null; then
        git_version=$(git --version | awk '{print $3}')
        echo "Git版本: $git_version"
    fi
    # 检查Docker
    if command -v docker &> /dev/null; then
        docker_version=$(docker --version | awk '{print $3}' | sed 's/,//')
        echo "Docker版本: $docker_version"
    fi
}
check_all_versions

Python版本检测脚本

#!/usr/bin/env python3
import subprocess
import sys
import platform
def get_command_version(command):
    """获取命令版本"""
    try:
        result = subprocess.run([command, '--version'], 
                              capture_output=True, 
                              text=True, 
                              timeout=5)
        return result.stdout.strip() or result.stderr.strip()
    except:
        return f"{command} not found"
def check_versions():
    """检查多个软件版本"""
    print("=" * 40)
    print("系统信息")
    print("=" * 40)
    print(f"Python: {sys.version}")
    print(f"系统: {platform.system()} {platform.release()}")
    commands = ['node', 'npm', 'git', 'docker', 'java', 'go', 'rustc']
    print("\n" + "=" * 40)
    print("软件版本")
    print("=" * 40)
    for cmd in commands:
        version = get_command_version(cmd)
        if 'not found' in version:
            print(f"{cmd}: {version}")
        else:
            # 格式化输出
            if cmd == 'node':
                v = version.replace('v', '')
                print(f"{cmd}: {v}")
            else:
                print(f"{cmd}: {version}")
def compare_version(version1, version2):
    """比较两个版本号"""
    v1_parts = [int(x) for x in version1.split('.')]
    v2_parts = [int(x) for x in version2.split('.')]
    # 补齐位数
    while len(v1_parts) < len(v2_parts):
        v1_parts.append(0)
    while len(v2_parts) < len(v1_parts):
        v2_parts.append(0)
    for i in range(len(v1_parts)):
        if v1_parts[i] > v2_parts[i]:
            return 1
        elif v1_parts[i] < v2_parts[i]:
            return -1
    return 0
def check_minimum_version(software, min_version):
    """检查最低版本要求"""
    version = get_command_version(software)
    if 'not found' in version:
        return False, f"{software} 未安装"
    # 提取版本号
    version_num = version.split()[-1].lstrip('v').rstrip(',')
    result = compare_version(version_num, min_version)
    if result >= 0:
        return True, f"{software} {version_num} >= {min_version}"
    else:
        return False, f"{software} {version_num} < {min_version}"
if __name__ == "__main__":
    check_versions()
    print("\n" + "=" * 40)
    print("最低版本要求检查")
    print("=" * 40)
    # 定义最低版本要求
    requirements = {
        'python3': '3.6.0',  # 注意:这里检查的是python3命令
        'node': '12.0.0',
        'git': '2.20.0'
    }
    for software, min_version in requirements.items():
        ok, message = check_minimum_version(software, min_version)
        icon = "✅" if ok else "❌"
        print(f"{icon} {message}")

PowerShell版本检测脚本 (Windows)

# Windows系统版本检测脚本
function Get-SoftwareVersion {
    param(
        [string]$SoftwareName
    )
    switch ($SoftwareName) {
        "Python" {
            try {
                $version = python --version 2>&1
                $version = $version -replace "Python ", ""
                return $version
            } catch {
                return "未安装"
            }
        }
        "Node.js" {
            try {
                $version = node --version
                $version = $version -replace "v", ""
                return $version
            } catch {
                return "未安装"
            }
        }
        "Git" {
            try {
                $version = git --version
                $version = $version -replace "git version ", ""
                return $version
            } catch {
                return "未安装"
            }
        }
        default {
            try {
                $version = & $SoftwareName --version 2>&1
                return $version
            } catch {
                return "未安装"
            }
        }
    }
}
# 检查注册表中的软件版本
function Get-RegistrySoftwareVersion {
    param(
        [string]$SoftwareName
    )
    $paths = @(
        "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*",
        "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
    )
    foreach ($path in $paths) {
        Get-ItemProperty $path | Where-Object {
            $_.DisplayName -like "*$SoftwareName*"
        } | Select-Object DisplayName, DisplayVersion
    }
}
# 主检测函数
function Check-Environments {
    Write-Host "=" * 50
    Write-Host "环境检测报告" -ForegroundColor Green
    Write-Host "=" * 50
    $softwares = @("Python", "Node.js", "Git", "npm", "docker")
    foreach ($software in $softwares) {
        $version = Get-SoftwareVersion -SoftwareName $software
        $color = if ($version -ne "未安装") { "Green" } else { "Red" }
        Write-Host "$software : " -NoNewline
        Write-Host $version -ForegroundColor $color
    }
    # 检查Visual Studio Build Tools
    Write-Host "`n检查Visual Studio组件:" -ForegroundColor Yellow
    $vsInfo = Get-RegistrySoftwareVersion -SoftwareName "Visual Studio"
    if ($vsInfo) {
        Write-Host "Visual Studio: $($vsInfo.DisplayVersion)" -ForegroundColor Green
    }
}
# 执行检测
Check-Environments

版本比较工具函数

def parse_version(version_str):
    """解析版本字符串为元组"""
    # 处理前缀 (如 v1.0.0, version 2.0.0)
    version_str = version_str.lstrip('vV').strip()
    if ' ' in version_str:
        version_str = version_str.split()[-1]
    parts = version_str.split('.')
    versions = []
    for part in parts:
        try:
            # 处理数字部分
            num = ''
            for char in part:
                if char.isdigit():
                    num += char
                else:
                    break
            versions.append(int(num) if num else 0)
        except ValueError:
            versions.append(0)
    return tuple(versions)
def version_greater_than(v1, v2):
    """检查版本v1是否大于v2"""
    v1_parts = parse_version(v1)
    v2_parts = parse_version(v2)
    # 补齐到相同长度
    max_len = max(len(v1_parts), len(v2_parts))
    v1_parts = v1_parts + (0,) * (max_len - len(v1_parts))
    v2_parts = v2_parts + (0,) * (max_len - len(v2_parts))
    return v1_parts > v2_parts
def version_in_range(version, min_version=None, max_version=None):
    """检查版本是否在范围内"""
    if min_version and not version_greater_than(version, min_version):
        return False
    if max_version and version_greater_than(version, max_version):
        return False
    return True
# 使用示例
if __name__ == "__main__":
    # 版本比较
    print(version_greater_than("3.9.0", "3.8.5"))  # True
    print(version_greater_than("v2.0.0", "1.9.9"))  # True
    # 版本范围检查
    print(version_in_range("10.0.0", min_version="9.0.0", max_version="11.0.0"))  # True
    print(version_in_range("12.0.0", min_version="9.0.0", max_version="11.0.0"))  # False

自动化版本检查和使用建议

周期性版本检查脚本

#!/bin/bash
# 版本检测与通知脚本
LOG_FILE="/var/log/version_check.log"
NOTIFY_EMAIL="admin@example.com"
check_and_notify() {
    local software=$1
    local min_version=$2
    local current_version=$3
    if [ "$(printf '%s\n' "$min_version" "$current_version" | sort -V | head -n1)" != "$min_version" ]; then
        echo "警告: $software 版本 $current_version 低于最低要求 $min_version" | tee -a $LOG_FILE
        # 可以添加邮件通知
        # echo "$software 版本需要更新" | mail -s "软件版本警告" $NOTIFY_EMAIL
    else
        echo "✓ $software $current_version 满足要求" >> $LOG_FILE
    fi
}
# 定期执行检查
while true; do
    echo "=== $(date) ===" >> $LOG_FILE
    # 检查关键软件版本
    python_version=$(python3 --version 2>&1 | awk '{print $2}')
    node_version=$(node --version 2>&1 | sed 's/v//')
    check_and_notify "Python" "3.8.0" "$python_version"
    check_and_notify "Node.js" "14.0.0" "$node_version"
    # 等待24小时
    sleep 86400
done

使用建议

  1. 跨平台兼容性:在编写检测脚本时考虑Windows/Linux/macOS差异
  2. 错误处理:添加超时机制和异常捕获
  3. 日志记录:记录版本检测结果以便追踪
  4. 定期检查:设置定时任务自动检查版本更新
  5. 版本约束:明确最低版本要求和兼容性范围
  6. 输出格式化:清晰的输出便于阅读和解析

根据实际需求选择合适的脚本类型,可以在CI/CD流程或部署脚本中集成这些检测功能。

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