VBScriptのコードを動的に実行するを改良する

処理のタイミングをリアルタイムに近づける。

vbs.py

コマンドを渡すサーバーとして動く。
import http.server as s
from urllib.parse import urlparse
from urllib.parse import parse_qs
from urllib.parse import unquote
import sqlite3

codes = []

class HTTPHandler(s.BaseHTTPRequestHandler):

	def do_GET(i):
		global codes
		p = parse_qs(urlparse(i.path).query)
		if 'code' in p: codes.append(p['code'][0])
		if len(codes) > 0:
			data = codes[0]
			if 'done' in p: codes.pop(0)
		else: data = ''
		i.do(data)
		if data == '__QUIT__': quit()

	def do(i,data):
		body = str(data)
		body = body.encode()
		i.send_response(200)
		i.send_header('Content-type','text/plain; charset=utf-8')
		i.send_header('Content-length',len(body))
		i.end_headers()
		i.wfile.write(body)


if __name__=='__main__':
	host = 'localhost'
	port = 22219
	httpd = s.HTTPServer((host,port),HTTPHandler)
	httpd.serve_forever()

execute.vbs

コマンドを受け取り、実行する。
Const URL = "//localhost:22219/"

Do
	' Connect to server
	Dim s
	On Error Resume Next
		s = Req(URL)
		'MsgBox s
		If s = "__QUIT__" Then
			Exit Do
		End If
		If Err.Number <> 0 Then
			Exit Do
		End If
	On Error Goto 0

	If s = "" Then
		Set WshShell = WScript.CreateObject("WScript.Shell")
		Call WshShell.Run("wait.vbs",0,True)
	Else
		' Process a task
		On Error Resume Next
			r = Execute(s)
			'MsgBox r
			If Err.Number <> 0 Then
				'ERROR
			End If
		On Error Goto 0

		' Send the task done
		On Error Resume Next
			s = Req(URL&"?done=1")
			'MsgBox s
			If Err.Number <> 0 Then
				Exit Do
			End If
		On Error Goto 0
	End If
Loop

Function Req(uri)
	Dim oXMLHTTP
	Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")
	oXMLHTTP.Open "GET", uri, False
	oXMLHTTP.setRequestHeader "If-Modified-Since", "Thu, 01 Jun 1970 00:00:00 GMT"
	oXMLHTTP.Send
	Dim data
	If oXMLHTTP.Status = 200 Then
		data = oXMLHTTP.responseText
	Else
		data = ""
	End If
	Req = data
End Function

wait.vbs

execute.vbsでWScript.Sleepを使うと不正なプログラムとみなされて削除されるので、WScript.Sleepを別のプログラムとする。
WScript.Sleep 1000

  1. python vbs.pyを実行してサーバーを設ける
  2. VBSのコード execute.vbs を実行する
  3. 好きなタイミングでサーバーにコードを登録する:
    • http://localhost:22219/?code=Dim%20n
    • http://localhost:22219/?code=n%3D10
    • http://localhost:22219/?code=MsgBox%20n
  4. http://localhost:22219/?code=__QUIT__で終了する
2020/02/29 15:35
タグ