1. 程式人生 > 其它 >VBSscript實現後臺執行Windows bat指令碼

VBSscript實現後臺執行Windows bat指令碼

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

--THE END--