VBScript 是Visual Basic 語言的輕量級版本,本文介紹使用VBS實現在后台運行bat腳本。
先編寫一個簡單的bat腳本(test_bat.bat):使用Python打開一個簡單的 http 服務器
@echo off
echo start
cmd /k "python -m http.server 8100"
echo end
pause
下面來測試一下這個腳本,雙擊test_bat.bat,會打開如下窗口:

瀏覽器訪問 http://127.0.0.1:8100/

可以看到HTTP服務搭建成功。
也可以使用 netstat
命令查看8100端口對應服務是否啟動:
$ netstat -nao | findstr 8100
TCP 0.0.0.0:8100 0.0.0.0:0 LISTENING 17220
TCP 127.0.0.1:1024 127.0.0.1:8100 TIME_WAIT 0
$
$ tasklist | findstr 17220
python.exe 17220 Console 1 18,800 K
如何實現在后台運行呢?可以使用VBScript來實現。
編寫vbs文件test_bat.vbs:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "test_bat.bat" & Chr(34), 0
0
表示后台運行,如果設置為1,會顯示cmd窗口。
雙擊test_bat.vbs運行,瀏覽器訪問 http://127.0.0.1:8100/ 查看服務是否啟動 或者使用如下命令:
$ netstat -nao | findstr 8100
TCP 0.0.0.0:8100 0.0.0.0:0 LISTENING 1788
$ tasklist | findstr 1788
python.exe 1788 Console 1 18,680 K
可以看到HTTP server啟動成功。
殺掉HTTP server:
$ taskkill -pid 1788 -f -t
SUCCESS: The process with PID 1788 (child process of PID 18576) has been terminated.
如果bat腳本需要傳入參數怎么實現呢?可以使用WScript.Arguments對象獲取參數,下面直接給出實現方式,將端口號作為參數傳入:
test_bat2.bat:
@echo off
echo start
python -m http.server %1
echo end
pause
test_bat2.vbs:
dim args
Set args = WScript.Arguments
Set WshShell = CreateObject("WScript.Shell")
WshShell.run "cmd /c " &args(0) &args(1),0
cmd命令窗口運行
$ test_bat2.vbs test_bat2.bat " 8100"
在實際使用過程中,通常不會手動雙擊運行腳本,比如在自動化測試中,需要自動啟動一個tshark抓包程序, 我們只需要它在后台運行。下面舉一個Python運行bat腳本的示例程序。
def start_bat(self, port):
"""啟動 HTTP server
:port: 服務端口號
"""
self.stop_process(port)
dir_path = os.path.dirname(os.path.realpath(__file__)) # 當前路徑
print(dir_path)
os.system(f'{dir_path}/test_bat.vbs "{dir_path}/test_bat.bat" " {port}"')
for l in range(3):
sleep(3)
if self.check_process(port):
print("http server successfully")
return True
print("http server started failed")
return False
完整代碼:https://github.com/hiyongz/ShellNotes/blob/main/test_vbs.py