首页 > 解决方案 > 检查用户是否使用 VBScript 登录您的工作站

问题描述

我需要一个解决方案来执行script检查用户是否登录到您的工作站。

我已在文件中存储了要质疑的恶化清单serverlist_login.txt

如果用户已登录,我们将用户名写入文件中results_login.txt

我试过这个脚本没有成功,但对于所有工作站,我username总是以用户登录到工作站的身份出现。这是不可能的

文件results_login.txt输出:

Login Results
 Date And Time : 24/08/2021 11:59:39

 User is connected  : worstation_01
MyDomain\MyUserName
 User is connected  : worstation_02
MyDomain\MyUserName
 User is connected  : worstation_03
MyDomain\MyUserName

有什么建议吗?

Const ForReading = 1, ForWrite = 2, ForAppend = 8

Set Fso = CreateObject("Scripting.FileSystemObject")    
Set wmi = GetObject("winmgmts:\\.\root\cimv2")
Set systems = wmi.ExecQuery("select * from Win32_ComputerSystem")

If Fso.FileExists(Fso.GetParentFolderName(WScript.ScriptFullName) & "\serverlist_login.txt") Then

Set Ts = Fso.OpenTextFile("serverlist_login.txt", ForReading)
strText = Ts.ReadAll
Ts.Close

For Each i In Split(strText, vbCrLf)
   For Each system In systems
      If system.UserName <> "" Then
         Results1 = Results1 & " User is connected  : " & i & vbCrLf & system.username & vbCrLf 
      Else
         Results2 = Results2 & " No user is connected : " & i & vbCrLf
      End If 
   Next
Next

Set Ts = Fso.CreateTextFile("results_login.txt")
Ts.WriteLine "Login Results" & vbCrLf & " Date And Time : " & Now & Vbcrlf
Ts.WriteLine Results1
Ts.WriteLine Results2
Ts.Close()  

Else
   MsgBox vbTab &_
      "Error" & vbcrlf &_
      "Missing, the server.txt to process. You" & vbCrLf & _
      "must create a servers.txt with an IP or" & vbCrLf & _
      "Computer Name, with one per line",4128,"Error"   
End If

更新#01

For Each i In Split(strText, vbCrLf)
   For Each system In Wmi.ExecQuery("select * from Win32_ComputerSystem where Name = '" & i & "'")
      If system.UserName <> "" Then
         Results1 = Results1 & " User is connected  : " & i & vbCrLf & system.username & vbCrLf 
      Else
         Results2 = Results2 & " No user is connected : " & i & vbCrLf
      End If 
   Next
Next

标签: authenticationvbscript

解决方案


为了说明有问题的循环,因为注释会阻止正确的格式:

For Each i In Split(strText, vbCrLf)
   Set wmi = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & i & "\root\cimv2")
   Set colItems = wmi.ExecQuery("select * from Win32_ComputerSystem")
   For Each Item In colItems
      If Item.UserName <> "" Then
         Results1 = Results1 & " User is connected  : " & i & vbCrLf & Item.username & vbCrLf 
      Else
         Results2 = Results2 & " No user is connected : " & i & vbCrLf
      End If 
   Next
Next

您是否看到变量i替换了.上述期间的位置?

此外,您的变量systems会误导您。这实际上只是 WMI 为当前系统返回的项目集合。

所以本质上,上面的主循环枚举了i文本文件中的所有系统;wmi然后通过(模拟您的用户帐户上下文)连接到这些系统;colItems然后从该系统中提取 Win32_ComputerSystem 项的集合;最后,枚举item集合中的每个以查看找到了哪些用户名。


推荐阅读