Windows Batch - 获取当前登录用户的名称

Windows Batch - 获取当前登录用户的名称

为了对大型网络进行小规模缓解,利用 cmd.exe 替换 Windows 修复中的 utilman.exe,然后更改用户密码,我正在编写一个基于 EventSentry 工具的小脚本,它将检测 utilman.exe 是否已更改,我可以向其附加操作。但此检测将在攻击者已登录本地计算机后进行。因此,我正在编写一个脚本,它将更改访问权限,并阻止删除和重命名 utilman.exe,我想为当前登录的用户添加密码更改,然后注销。

这是我目前所拥有的:

 @ECHO off
 takeown /f c:\windows\system32\utilman.exe
 icacls c:\windows\system32\utilman.exe /deny *S-1-1-0:(DE,WD,AD,RX)
 net user [NeedToGetLogedUser] 123456
 shutdown -L

我附加的操作将在另一个用户(而不是实际登录的用户)下执行此脚本。因此,我需要获取登录到计算机的实际当前用户,而不是此脚本将在其下运行的用户。

我在想:

C:\Users\MyUser>query user
USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
>MyUser              console             1  Active      none   7/9/2020 6:27 PM

但我不知道如何解析结果只是为了单独获取“MyUser”(使用 findstr)并将其与 net user 命令一起使用。

答案1

for /F "tokens=2 delims==" %f in ('wmic computersystem get username /value ^| find "="') do set "ConsoleUser=%f"

输出:

" \>set "ConsoleUser=COMPUTERORDOMAINNAME\username

在批处理文件中运行时,将 % 替换为 %%

for /F "tokens=2 delims==" %%f in ('wmic computersystem get username /value ^| find "="') do set "ConsoleUser=%%f"
echo %ConsoleUser%

答案2

感谢大家的回复。这帮助我找到了解决方案。我最终编写了这个脚本,它完全满足了我的需求 :)

@ECHO off
set ConsoleUser=None
takeown /f c:\windows\system32\utilman.exe
icacls c:\windows\system32\utilman.exe /deny *S-1-1-0:(DE,WD,AD,RX)
for /F "tokens=1" %%f in ('query user ^| find ">"') do set "ConsoleUser=%%f"
net user %ConsoleUser:~1% 123456
shutdown -L

该脚本会限制utilman.exe的执行、删除和重命名,并重置已登录用户的密码,然后注销用户。这样攻击者就无法再次修改utilman.exe或执行它,用户的密码就被更改了。

再次感谢!

答案3

如果您想拆分用户名和域,然后使用它为用户设置 localappdata 路径,请按照以下方法操作

:: Get current session user's Domain and username
for /F "tokens=2 delims==" %%f in ('wmic computersystem get username /value ^| find "="') do set "ConsoleUser=%%f"
:: Split and set variables for current session user's Domain and username
FOR /f "tokens=1 delims=\" %%a IN ("%ConsoleUser%") do set "domain=%%a"
FOR /f "tokens=2 delims=\" %%b IN ("%ConsoleUser%") do set "user=%%b"
:: Echo username and domain
echo %domain%
echo %user%
:: Set variable localappdata path and echo
set localappdata "C:\users\%user%\AppData\Local"
echo %localappdata%

答案4

..对于帽子戏法 - 与上面使用 vbscript 相同

Set wshShell = WScript.CreateObject("WScript.Shell")
 
' Get the username 
strUsername = Get_LoggedOnUserName()
 
' Set localappdata variable and then echo it out
 Dim localappdata 
localappdata = "C:\users\" & strUsername & "\appdata\local"
wscript.echo localappdata

Function Get_LoggedOnUserName
  Dim Array
  strComputer = "." 
  Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") 
  Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_ComputerSystem",,48) 
 
  For Each objItem in colItems 
    Array = Split(objItem.UserName, "\", -1, 1)  
 
    Get_LoggedOnUserName = Array(1)
  Next 
 
End Function

相关内容