VBScript输入框提交凭据后如何打开文件?技术求助
VBScript 实现带整合账号输入框并自动传递密码执行程序
问题分析
你当前的脚本存在两个核心问题:
runas命令无法直接接收inputBox传入的密码,必须交互式手动输入,导致弹出命令行窗口重复要求输入密码- 两个独立的
inputBox不符合你"独立窗口、确定取消按钮上下排列"的需求
解决方案
下面的脚本通过MSHTA创建整合式的用户名密码输入对话框,同时利用SendKeys自动向runas窗口传递密码,解决上述问题:
Set objShell = CreateObject("WScript.Shell") Set objFSO = CreateObject("Scripting.FileSystemObject") ' 构建整合式登录对话框的HTA代码 strHTACode = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>" & _ "<title>身份验证</title></head><body style='padding:20px;'>" & _ "<div style='text-align:center;'>" & _ "<p><label>用户名:<input type='text' id='txtUser' style='width:180px;'></label></p>" & _ "<p><label>密 码:<input type='password' id='txtPass' style='width:180px;'></label></p>" & _ "<p><button onclick='submitForm()' style='width:80px;'>确定</button></p>" & _ "<p><button onclick='window.close()' style='width:80px;'>取消</button></p>" & _ "</div>" & _ "<script language='VBScript'>" & _ "Sub submitForm()" & _ " Dim user, pass" & _ " user = Document.getElementById(""txtUser"").Value" & _ " pass = Document.getElementById(""txtPass"").Value" & _ " ' 将结果写入注册表临时存储" & _ " CreateObject(""WScript.Shell"").RegWrite ""HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce\\HTAResult"", user & ""|"" & pass" & _ " window.close()" & _ "End Sub" & _ "</script></body></html>" ' 生成临时HTA文件 strTempHTA = objFSO.GetSpecialFolder(2) & "\temp_auth.hta" Set objFile = objFSO.CreateTextFile(strTempHTA, True, True) objFile.Write strHTACode objFile.Close ' 运行HTA对话框并等待用户操作 objShell.Run "mshta.exe """ & strTempHTA & """", 1, True ' 读取用户输入的账号密码 On Error Resume Next strResult = objShell.RegRead("HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce\HTAResult") objShell.RegDelete "HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce\HTAResult" On Error GoTo 0 ' 清理临时文件 objFSO.DeleteFile strTempHTA ' 处理用户输入 If InStr(strResult, "|") > 0 Then arrCreds = Split(strResult, "|") strUserName = arrCreds(0) strPassword = arrCreds(1) ' 启动runas命令,延迟后自动输入密码 objShell.Run "runas /user:" & strUserName & " ""wscript.exe c:\path\myscript.vbs""", 1, False WScript.Sleep 1200 ' 等待runas窗口加载,可根据系统速度调整 objShell.SendKeys strPassword & "{ENTER}" Else ' 用户点击取消,直接退出 WScript.Quit End If
关键说明
- 整合式对话框:通过MSHTA实现了包含用户名、密码输入框,以及上下排列的确定/取消按钮的独立窗口,符合你的界面需求
- 密码自动传递:利用
SendKeys模拟键盘输入,将HTA对话框获取的密码自动传入runas窗口,避免手动重复输入 - 临时文件处理:自动生成和删除临时HTA文件,无残留文件
- 错误处理:加入注册表读取的错误捕获,避免用户取消时脚本报错
注意事项
- 确保目标脚本路径
c:\path\myscript.vbs正确,且当前用户有访问权限 - 若
SendKeys失效,可适当调整WScript.Sleep的延迟时间(单位:毫秒) - 如果你需要隐藏
runas窗口,可将Run方法的第二个参数改为0,但可能导致SendKeys无法定位窗口,建议保持窗口可见
内容的提问来源于stack exchange,提问作者MASONNET
相关产品推荐
相关产品推荐

