本文目录导读:

我来帮你写一个自动下载并安装的脚本,根据不同的操作系统和需求,我提供几个常用示例:
Windows PowerShell 脚本
# download-install.ps1
param(
[string]$Url = "https://example.com/software.exe",
[string]$Filename = "installer.exe",
[string]$InstallPath = "$env:TEMP\$Filename"
)
# 下载文件
Write-Host "正在下载 $Filename..."
try {
Invoke-WebRequest -Uri $Url -OutFile $InstallPath
Write-Host "下载完成!"
} catch {
Write-Error "下载失败: $($_.Exception.Message)"
exit 1
}
# 静默安装(根据安装程序类型调整参数)
Write-Host "正在安装..."
try {
Start-Process -FilePath $InstallPath -ArgumentList "/quiet", "/norestart" -Wait
Write-Host "安装完成!"
} catch {
Write-Error "安装失败: $($_.Exception.Message)"
exit 1
}
# 清理临时文件
Remove-Item $InstallPath -Force
Write-Host "临时文件已清理"
Linux Bash 脚本
#!/bin/bash
# download-install.sh
# 定义变量
DOWNLOAD_URL="https://example.com/software.deb"
FILENAME="software.deb"
TEMP_DIR="/tmp/software_install"
# 创建临时目录
mkdir -p $TEMP_DIR
cd $TEMP_DIR
# 下载文件
echo "正在下载 $FILENAME..."
if wget -q $DOWNLOAD_URL -O $FILENAME; then
echo "下载完成!"
else
echo "下载失败!"
exit 1
fi
# 根据文件类型安装
case $FILENAME in
*.deb)
echo "安装 DEB 包..."
sudo dpkg -i $FILENAME
sudo apt-get install -f -y # 修复依赖
;;
*.rpm)
echo "安装 RPM 包..."
sudo rpm -ivh $FILENAME
;;
*.tar.gz|*.tgz)
echo "解压 tar 包..."
tar -xzf $FILENAME -C /opt
;;
*)
echo "不支持的文件格式!"
exit 1
;;
esac
# 清理临时文件
cd /
rm -rf $TEMP_DIR
echo "安装完成!"
通用 Python 脚本
#!/usr/bin/env python3
# download_install.py
import os
import sys
import requests
import subprocess
import tempfile
import platform
def download_file(url, filename):
"""下载文件"""
print(f"正在下载 {filename}...")
try:
response = requests.get(url, stream=True)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
block_size = 8192
downloaded = 0
with open(filename, 'wb') as file:
for chunk in response.iter_content(chunk_size=block_size):
if chunk:
file.write(chunk)
downloaded += len(chunk)
# 显示进度
if total_size > 0:
progress = (downloaded / total_size) * 100
print(f"\r下载进度: {progress:.1f}%", end='')
print("\n下载完成!")
return True
except Exception as e:
print(f"下载失败: {e}")
return False
def install_windows(installer_path):
"""Windows 安装"""
try:
subprocess.run([installer_path, '/quiet', '/norestart'], check=True)
print("安装完成!")
except subprocess.CalledProcessError as e:
print(f"安装失败: {e}")
def install_linux(installer_path):
"""Linux 安装"""
ext = os.path.splitext(installer_path)[1]
try:
if ext == '.deb':
subprocess.run(['sudo', 'dpkg', '-i', installer_path], check=True)
subprocess.run(['sudo', 'apt-get', 'install', '-f', '-y'], check=True)
elif ext == '.rpm':
subprocess.run(['sudo', 'rpm', '-ivh', installer_path], check=True)
else:
print(f"不支持的文件格式: {ext}")
except subprocess.CalledProcessError as e:
print(f"安装失败: {e}")
def main():
# 配置
download_url = "https://example.com/software.exe" # 修改为实际下载地址
system = platform.system()
# 创建临时文件
with tempfile.NamedTemporaryFile(delete=False, suffix='.exe' if system == 'Windows' else '.deb') as temp_file:
temp_path = temp_file.name
try:
# 下载文件
if not download_file(download_url, temp_path):
return
# 根据系统安装
if system == 'Windows':
install_windows(temp_path)
elif system == 'Linux':
install_linux(temp_path)
else:
print(f"不支持的操作系统: {system}")
finally:
# 清理临时文件
if os.path.exists(temp_path):
os.remove(temp_path)
print("临时文件已清理")
if __name__ == "__main__":
main()
配置文件版本(灵活配置)
创建 config.json 配置文件:
{
"software": [
{
"name": "Chrome",
"url": "https://dl.google.com/chrome/install/latest/chrome_installer.exe",
"install_args": "/silent /install",
"platform": "windows"
},
{
"name": "VS Code",
"url": "https://code.visualstudio.com/sha/download?build=stable&os=linux-deb-x64",
"install_type": "deb",
"platform": "linux"
}
]
}
然后创建主脚本引用配置:
# main_installer.py
import json
import sys
from download_install import download_file, install_windows, install_linux
def load_config(config_file='config.json'):
with open(config_file, 'r') as f:
return json.load(f)
def main():
config = load_config()
for software in config['software']:
print(f"\n开始安装: {software['name']}")
# 执行下载和安装逻辑
# ...
if __name__ == "__main__":
main()
使用说明
-
Windows 用户:
- 右键点击
.ps1文件,选择"使用 PowerShell 运行" - 或运行:
powershell -ExecutionPolicy Bypass -File download-install.ps1
- 右键点击
-
Linux 用户:
- 赋予执行权限:
chmod +x download-install.sh - 运行:
./download-install.sh
- 赋予执行权限:
-
Python 用户:
- 安装依赖:
pip install requests - 运行:
python download_install.py
- 安装依赖:
注意事项
- 🔒 始终验证下载来源的安全性
- ⚡ 添加错误处理和日志记录
- 📝 根据具体软件调整安装参数(如静默安装参数)
- 🔄 考虑添加重试机制
- 🛡️ 确保有足够的权限执行安装
你可以根据实际需要修改这些脚本,例如添加多线程下载、断点续传、版本检查等功能。