萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 調用命令列實現 RAR 自動解壓:WScript.Shell + WinRAR 實戰

在無法安裝解壓組件的虛擬主機環境下,利用系統內建 WScript.Shell 調用 WinRAR.exe 實現伺服端自動解壓。零組件、零註冊、純腳本方案。

前置準備

  1. 上傳 WinRAR.exe (或官方免費 UnRAR.exe) 至伺服器目錄 (如 E:\Tools\)
  2. 確保 IIS 工作進程身份 (IUSR/ApplicationPoolIdentity) 對該目錄有讀取/執行權限
  3. 目標解壓目錄需有寫入權限

核心解壓代碼

<%
Dim rarPath, cmdPath, sourceRar, destDir, shell, cmdLine, retCode

' 路徑配置
rarPath   = "E:\Tools\WinRAR.exe"          ' 解壓程式路徑
sourceRar = Server.MapPath("uploads\data.rar")  ' 待解壓檔案
destDir   = Server.MapPath("extracted\")    ' 解壓目標目錄 (需存在)

' 建立 Shell 物件
Set shell = Server.CreateObject("WScript.Shell")

' 組裝命令列參數
' x = 解壓帶路徑  -o+ = 覆蓋既有  -p- = 無密碼  -ibck = 後台運行
cmdLine = """" & rarPath & """ x -o+ -p- -ibck """ & sourceRar & """ """ & destDir & """"

' 執行並等待完成 (bWaitOnReturn = True)
retCode = shell.Run(cmdLine, 0, True)  ' 0 = 隱藏視窗

Select Case retCode
    Case 0  : Response.Write "解壓成功"
    Case 1  : Response.Write "警告:非致命錯誤"
    Case 2  : Response.Write "錯誤:致命錯誤"
    Case 3  : Response.Write "錯誤:CRC 校驗失敗"
    Case 4  : Response.Write "錯誤:鎖定檔案"
    Case 5  : Response.Write "錯誤:記憶體不足"
    Case 6  : Response.Write "錯誤:建立檔案失敗"
    Case 7  : Response.Write "錯誤:使用者中止"
    Case 8  : Response.Write "錯誤:記憶體分配失敗"
    Case 255: Response.Write "錯誤:找不到 WinRAR 或參數錯誤"
    Case Else: Response.Write "未知返回碼:" & retCode
End Select

Set shell = Nothing
%>

WinRAR 命令列參數速查

| 參數 | 說明 | 常用組合 | |------|------|----------| | x | 解壓帶完整路徑 | 基礎參數 | | e | 解壓忽略路徑 (全部平鋪) | 單層輸出 | | -o+ | 覆蓋既有檔案 | 自動化必備 | | -o- | 跳過既有檔案 | 增量解壓 | | -p密碼 | 指定密碼 | -p123456 | | -p- | 無密碼 (抑制彈窗) | 批次處理必備 | | -ibck | 後台模式 (無 GUI) | 伺服端必備 | | -r | 遞迴子目錄 | 預設開啟 | | -ep1 | 排除基礎目錄層級 | 整理目錄結構 |

安全與穩健性加固

  • 路徑驗證:Server.MapPath 防止目錄遍歷攻擊
  • 檔案類型檢查:僅允許 .rar 副檔名上傳
  • 大小限制:防止解壓炸彈 (ZIP Bomb)
  • 超時控制:shell.Run 第三參數 True 會無限等待,生產環境建議包裝超時機制
  • 日誌記錄:記錄 retCode、耗時、檔案大小供審計

替代方案:純 VBScript 解壓 (無 WinRAR 依賴)

' 利用 Shell.Application COM 物件 (僅支援 ZIP)
Set shellApp = CreateObject("Shell.Application")
Set dest = shellApp.NameSpace(destDir)
Set source = shellApp.NameSpace(sourceZip)
dest.CopyHere source.Items, 4 + 16  ' 4=不顯示進度, 16=覆蓋
' 注意:此為異步操作,需輪詢檔案數判斷完成

WinRAR 方案支援 RAR 格式、密碼保護、大檔案分卷,是 ASP 伺服端解壓的最佳選擇。

copyright © 萬盛學電腦網 all rights reserved