脚本怎样检测程序版本更新

wen 实用脚本 32

本文目录导读:

脚本怎样检测程序版本更新

  1. HTTP请求比较版本号
  2. GitHub Releases API
  3. 服务器文件校验
  4. 自动更新脚本示例
  5. Bash脚本版本检测
  6. 配置文件base更新检测
  7. 更新检测最佳实践:

HTTP请求比较版本号

Python 示例

import requests
import json
from packaging import version
def check_update():
    # 当前程序版本
    current_version = "1.0.0"
    # 从服务器获取最新版本信息
    try:
        response = requests.get("https://your-server.com/version.json", timeout=5)
        data = response.json()
        latest_version = data["version"]
        # 比较版本
        if version.parse(latest_version) > version.parse(current_version):
            print(f"发现新版本: {latest_version}")
            print(f"更新内容: {data.get('changelog', '无')}")
            return True
        else:
            print("当前已是最新版本")
            return False
    except Exception as e:
        print(f"检查更新失败: {e}")
        return False
# 版本信息示例 (version.json)
"""
{
    "version": "1.1.0",
    "changelog": "修复了一些bug",
    "download_url": "https://example.com/download/new_version.zip"
}
"""

GitHub Releases API

import requests
def check_github_update():
    current_version = "v1.0.0"
    repo = "username/repo-name"
    try:
        # 获取最新release
        url = f"https://api.github.com/repos/{repo}/releases/latest"
        response = requests.get(url)
        latest = response.json()
        latest_version = latest["tag_name"]
        if latest_version > current_version:
            print(f"新版本: {latest_version}")
            print(f"下载: {latest['zipball_url']}")
            return True
    except Exception as e:
        print(f"检查失败: {e}")
# 需要设置一个release标签,如 v1.0.0, v1.1.0 等

服务器文件校验

import hashlib
import requests
def check_file_update():
    current_hash = "abc123..."  # 当前文件哈希值
    try:
        # 获取服务器文件
        response = requests.get("https://server.com/program.exe")
        file_content = response.content
        # 计算哈希值
        server_hash = hashlib.md5(file_content).hexdigest()
        if server_hash != current_hash:
            print("文件有更新,需要重新下载")
            return True
    except Exception as e:
        print(f"校验失败: {e}")

自动更新脚本示例

import os
import sys
import requests
import tempfile
import zipfile
import shutil
class AutoUpdater:
    def __init__(self, current_version, update_url):
        self.current_version = current_version
        self.update_url = update_url
    def check_update(self):
        """检查更新"""
        try:
            response = requests.get(self.update_url)
            data = response.json()
            return data["version"] > self.current_version, data
        except:
            return False, None
    def download_update(self, download_url):
        """下载更新包"""
        temp_dir = tempfile.mkdtemp()
        zip_path = os.path.join(temp_dir, "update.zip")
        response = requests.get(download_url, stream=True)
        with open(zip_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
        return zip_path
    def apply_update(self, zip_path):
        """应用更新"""
        # 解压到临时目录
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall("update_temp")
        # 备份当前文件
        if os.path.exists("backup"):
            shutil.rmtree("backup")
        shutil.copytree(".", "backup")
        # 更新文件
        for root, dirs, files in os.walk("update_temp"):
            for file in files:
                src_path = os.path.join(root, file)
                dst_path = os.path.join(".", file)
                shutil.copy2(src_path, dst_path)
        # 清理
        os.remove(zip_path)
        shutil.rmtree("update_temp")
# 使用示例
updater = AutoUpdater("1.0.0", "https://server.com/version.json")
has_update, info = updater.check_update()
if has_update:
    print(f"发现更新: {info['version']}")
    zip_path = updater.download_update(info['download_url'])
    updater.apply_update(zip_path)

Bash脚本版本检测

#!/bin/bash
# 当前版本
CURRENT_VERSION="1.0.0"
# 检查更新
check_update() {
    # 从服务器获取版本信息
    LATEST_VERSION=$(curl -s https://server.com/version.txt)
    if [ "$LATEST_VERSION" != "$CURRENT_VERSION" ]; then
        echo "发现新版本: $LATEST_VERSION"
        return 0
    else
        echo "已是最新版本"
        return 1
    fi
}
# 执行更新
if check_update; then
    echo "开始下载更新..."
    curl -O https://server.com/update.zip
    unzip -o update.zip
    rm update.zip
    echo "更新完成"
fi

配置文件base更新检测

import yaml
import requests
class ConfigBasedUpdater:
    def __init__(self, update_config_url):
        self.config_url = update_config_url
        self.config = None
    def get_config(self):
        """获取更新配置"""
        response = requests.get(self.config_url)
        self.config = yaml.safe_load(response.text)
        return self.config
    def check_updates(self):
        config = self.get_config()
        print("可用更新:")
        for update in config['updates']:
            print(f"- {update['version']}: {update['description']}")
            if update['required']:
                print("  [强制更新]")
# 配置文件示例 (update_config.yaml)
"""
updates:
  - version: "2.0.0"
    description: "重大更新,添加新功能"
    required: true
    download_url: "https://example.com/v2.0.0.zip"
  - version: "1.5.0"
    description: "性能优化"
    required: false
    download_url: "https://example.com/v1.5.0.zip"
"""

更新检测最佳实践:

  1. 版本号规范:使用语义化版本(SemVer):主版本.次版本.修订号
  2. 网络超时处理:设置合理的超时时间
  3. 增量更新:只下载差异部分
  4. 回滚机制:更新失败能恢复
  5. 验证完整性:下载后校验文件完整性
  6. 用户通知:非强制更新时要提供选择

选择哪种方式取决于你的程序类型、部署环境和更新频率。

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