batch file variables view client ip - batch-file

Trying to record a user client IP for a remote session. Currently have a little batch file recording logon times, and hostname. Need to also include the client IP address;
Currently using this;
reg query "HKEY_CURRENT_USER\Volatile Environment" /s > %temp%\IPINFO.txt
findstr /L ViewClient_IP_Address %temp%\IPINFO.txt > %temp%\IPRESULTS.txt
FOR /F “tokens=* delims= ” %%a in (%temp%\IPRESULTS.txt) do set IP=%%a
del %temp%\IPRESULTS.txt
set IP=%IP%
echo Login ,%Date%,%Time%,%computername%,%clientname%,%IP% >> Y:\%username%.csv
The registry key viewclient_ip_Address has the information I need, but the registry folder it sits within changes name each time so I'm having to export the whole directory and then filter for the key itself.
I just need to add the information from that IPRESULTS.txt into my end .csv file but struggling with writing it up.
Any help appreciated.

Is this what you're looking for? (The for-loop runs the command and parses it's output in memory)
For /F "EOL=HTokens=2*" %%H In ('^""%__AppDir__%reg.exe" Query "HKCU\Volatile Environment" /V ViewClient_IP_Address 2^>NUL^"')Do Set "IP=%%~I"
To find out more about how to use reg.exe with query, open up a Command Prompt window and enter reg query /?
If, as you've stated in your question, the required value and data is located under HKEY_CURRENT_USER\Volatile Environment but within a variable/unknown, subkey name, the help information should show you that you can use the /F option to locate your known value name, ViewClient_IP_Address, if you specify that the search is to locate a value using /V, it should retrieve the line you need.
For example, at the Command Prompt:
Reg Query "HKCU\Volatile Environment" /S /F "ViewClient_IP_Address" /V
Returns:
C:\Users\smith_ll>Reg Query "HKCU\Volatile Environment" /S /F "ViewClient_IP_Add
ress" /V
HKEY_CURRENT_USER\Volatile Environment\UnknownSubKey
ViewClient_IP_Address REG_SZ 192.168.1.15
End of search: 1 match(es) found.
You can then put that command into your for-loop, and pass its output through find.exe to isolate the line you need to parse. The underscore, for instance, looks unique to just the line you need. As we're already excluding any line beginning with H ,(with EOL=H), it will not match the End of search: 1 match(es) found. line:
Example:
For /F "EOL=HTokens=2*" %%H In ('^""%__AppDir__%reg.exe" Query "HKCU\Volatile Environment" /S /F "ViewClient_IP_Address" /V 2^>NUL^|"%__AppDir__%find.exe" "_"^"')Do #Set "IP=%%~I"
If you don't like the super long line, you can split into more using the caret:
For /F "EOL=HTokens=2*" %%H In ('^""%__AppDir__%reg.exe" Query^
"HKCU\Volatile Environment" /S /F "ViewClient_IP_Address" /V 2^>NUL^
^|"%__AppDir__%find.exe" "_"^"')Do #Set "IP=%%~I"

Related

export string value in a registry

i want to export HKEY_LOCAL_MACHINE\SOFTWARE\ABC\EFGH string XYZ value 12. i looked into regedit /e and Reg export. it gives options to export till HKEY_LOCAL_MACHINE\SOFTWARE\ABC\EFGH, but not my string value XYZ.
I can think of no native method of exporting just a particular value with its data directly as a .reg file.
The best advice would be that you parse the output from reg query for your particular value data, and save it as a reg add command to another batch file. Then when, or if, you need to replace that value data with the previously saved data, you can just run that saved batch file.
Below is a basic example, (designed only for use with value type REG_SZ). I've used a common registry subkey and value for demonstration purposes, (because yours was not clear to me); please replace those on lines 4 and 5 as per your specific requirements:
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "RegistryKey=HKEY_CURRENT_USER\Control Panel\Desktop"
Set "ValueName=Wallpaper"
Set "ValueData="
For /F "Tokens=*" %%G In ('%SystemRoot%\System32\reg.exe Query "%RegistryKey%"
/V "%ValueName%" 2^>NUL ^| %SystemRoot%\System32\findstr.exe /R "\<REG_SZ\>"'
) Do (Set "ValLine=%%G" & SetLocal EnableDelayedExpansion
For /F "UseBackQ Tokens=1,*" %%H In ('!ValLine:*%ValueName%^=!'
) Do EndLocal & Set "ValueData=%%I")
If Defined ValueData Echo #%%SystemRoot%%\System32\reg.exe Add "%RegistryKey%"^
/V "%ValueName%" /T REG_SZ /D "%ValueData:"=\"%" /F 1^>NUL 1>"%ValueName%.cmd"
If the string value is successfully found, its data will be saved to a local variable %ValueData%, for further use within the script if required. In addition, a batch file with the name of the registry value, should be output to the current directory. If you wish to change that name or location, please replace %ValueName%.cmd on the last line as needed. To restore the data at a later time just run the saved batch file.

Get install location from registry key value data

I basically want to know if its possible for me to get a path from the registry and use it in a Batch file.
Basically what I have is some code I've gather from this site
#echo off
reg query "HKLM\SOFTWARE\Wow6432Node\Rockstar Games\Grand Theft Auto V" /v "InstallFolder"
That line returns
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Rockstar Games\Grand Theft Auto V
InstallFolder REG_SZ D:\Rockstar Games\Grand Theft Auto V
All I want to do here is add the path of GTA to the batch file so I can then launch the executable (PlayGTAV.exe) through the batch file. The reason I'm not using the path i already know is because I want this batch file to work on some friends computers too.
#ECHO OFF
SETLOCAL
FOR /f "delims=" %%a IN ('reg query "HKLM\SOFTWARE\Embarcadero\Interbase\Servers" ^|find " REG_SZ "') DO (
SET "target=%%a"
)
SET "target=%target:*REG_SZ =%"
ECHO "%target%"
GOTO :EOF
This should demonstrate how - I've obviously used a different key.
The ^|find... finds the appropriate line containing the REG_SZ (the caret is used to tell cmd that the piping is of the reg query command, not part of the for) and the for /f "delims=" selects the entire line for application to %%a.
From there, it's simply a matter of applying substringing to the ordinary environment variable target (since substringing of the metavariable %%a is not allowed) - replace any characters before and including the first occurrence of REG_SZ+4spaces with nothing (the string between the = and terminal %

Use List of Windows accounts to add reg keys using SIDS

edit re explanation to improve answers.
Project
As a third party engineer I am attending a site to install a piece of Software. The Infrastructure is "very" locked down. I will be supplied with an admin account for the day to install the software. However, to make the software work properly FOR ALL USERS (not just admin logged in) I have been instructed by IT dept. to manually create a KEY and then add a string value within created key for every user account on the PC. Our software in a standard environment caters for this with an all users reg key but it doesn't run (not allowed - don't ask!) in these specific places.
The location of where they want the the KEY is within the HKEY_USERS path in the reg:-
HKEY_USERS\S-1-5-21-XXXXXXXXX-XXXXXXXXX-XXXXXXXXXX-XXXXX\Software\Microsoft\
so lets say 2 people logged in this PC and they need to use our software later on
john.jones
mary.shelley
I need to find the sid relating to john jones and go and add the key to his section in HKEY_USERS
I then need to find mary.shelley sid and then go and the key to her HKEY_USERS section, etc.
Now I know from the environments I work in there could be 20 + user acounts on there so really would like to avoid manually adding they keys over and over for all the accounts on every PC I'm installing at.
A log on script would be better, but this all I have to deal with at present.
State of Script Now
#echo off
REM Read file with user names
FOR /F "usebackq tokens=*" %%G in ("users.txt") do (
REM use user name to find SID
FOR /F "delims=" %%H IN ('"wmic useraccount where name='%%~G' get sid| findstr /vi "SID""') DO (
REM Strip trailing line with CR
FOR /F "delims= " %%I IN ("%%~H") DO (
REM %%I is now the SID of the USER
REG ADD "HKEY_USERS\%%I\Software\Microsoft\addstuffhere" /f
REG ADD "HKEY_USERS\%%I\Software\Microsoft\addstuffhere" /t REG_SZ /d "addstuffhere"" /f
)
)
)
This is pretty much automating the whole thing as planned; loops through a text file of user names of users who use the PC, grabs the SID, applies sid as variable, then is used to write the key in the right place for that user, and on through the list doing to same for every account listed.
The only part that may need altering is the WMIC section is not finding certain users who have bona fide windows accounts.
when I tested the working code on my laptop it worked fine for my administrator account, but me logged in as joe_blogs (e.g.) came up with "no instance available". Because in isolation the WMIC code just brought up only a few not all, so couldn't do what it needed to do.
I know from previous questions this WMIC code brings up every account:-
WMIC Path Win32_UserProfile Where "Special='False' And Not LocalPath='Null'" Get LocalPath,SID | find /v ""
Perhaps that can be incorporated into current working code to make sure every account is catered for.
I know the users all need to have logged in at each PC for this to work, so with regards to the list of user profiles, I can garner that on the day asking "who of your users needs to use our stuff on the PC's" and make the users.txt
thanks - hope that really explains it :/
edit instructions for what I have been asked to do (altered key names slightly for privacy)
1. Log on to the PC with a standard technician admin account
2. Open regedit.exe
3. Navigate to* HKEY_USERS\S-1-5-21-XXXXXXXXX-XXXXXXXXX-XXXXXXXXXX- XXXXX\Software\Microsoft\Terminal Server Client\Default\Addins\
a. Right-click Addins > New > Key and create foo
b. Right-click foo > New > String Value and create Name
c. Double-click Name and in Value Data enter† C:\foo\file\foo.dll
4. Repeat step 3 for each user: it should be possible to edit the SID in an exported key by right-clicking on the next
HKEY_USERS entry > Rename > Ctrl+C > Esc then replacing the SID in the exported reg key – this has not been tested but may be worth trying
*The user SID is unique so this has to be done per user. If there are a lot of users listed in the registry it is possible to find which SID belongs to which user by checking the key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
After reading your edit, it sounds like there's some room to wiggle here. If we take 2 small liberties, this could be done in a single command line. If one or both liberties can't be taken, let me know.
If WMIC isn't required, and if we can target all SIDs present rather than trying to match names to SIDs, then 'reg.exe' and 'for' can do this quickly. Here's an example with sample output:
(Optional) Enum Profiles:
cmd:
for /f "delims=\ tokens=2" %A in ('reg query hku ^| findstr /i "S-1-5-21-" ^| findstr /v /i "_Classes"') do #echo ;[i] Profile Found: {%A}
output:
;[i] Profile Found: {S-1-5-21-277974881-2357464463-7727422770-1001}
;[i] Profile Found: {S-1-5-21-277974881-2357464463-7727422770-1002}
;[i] Profile Found: {S-1-5-21-277974881-2357464463-7727422770-1007}
Add Key+Value
cmd:
for /f "delims=\ tokens=2" %A in ('reg query hku ^| findstr /i "S-1-5-21-" ^| findstr /v /i "_Classes"') do #(reg add "hku\%A\Software\Microsoft\Terminal Server Client\Default\Addins\FooKey" /v FooName /t REG_SZ /d "C:\foo\file\foo.dll" /f >nul 2>&1 && (echo ;[i] Reg Key Added {%A}) || (echo ;[i] Reg Key Failed To Add {%A}))
output:
;[i] Reg Key Added {S-1-5-21-277974881-2357464463-7727422770-1001}
;[i] Reg Key Added {S-1-5-21-277974881-2357464463-7727422770-1002}
;[i] Reg Key Added {S-1-5-21-277974881-2357464463-7727422770-1007}
(Optional) Verify Success:
cmd:
for /f "delims=\ tokens=2" %A in ('reg query hku ^| findstr /i "S-1-5-21-" ^| findstr /v /i "_Classes"') do #(reg query "hku\%A\Software\Microsoft\Terminal Server Client\Default\Addins\FooKey" /v FooName 2>nul || echo ;[e] Couldn't Find Key {%A})
output:
HKEY_USERS\S-1-5-21-277974881-2357464463-7727422770-1001\Software\Microsoft\Terminal Server Client\Default\Addins\FooKey
FooName REG_SZ C:\foo\file\foo.dll
HKEY_USERS\S-1-5-21-277974881-2357464463-7727422770-1002\Software\Microsoft\Terminal Server Client\Default\Addins\FooKey
FooName REG_SZ C:\foo\file\foo.dll
HKEY_USERS\S-1-5-21-277974881-2357464463-7727422770-1007\Software\Microsoft\Terminal Server Client\Default\Addins\FooKey
FooName REG_SZ C:\foo\file\foo.dll
Not sure if I am understanding your question. My first comment should have made it quite clear. You need to use a FOR /F command to capture the WMIC output. That is the only way you can assign the SID to a variable.
#echo off
REM Read file with user names
FOR /F "usebackq tokens=*" %%G in ("users.txt") do (
REM use user name to find SID
FOR /F "delims=" %%H IN ('"wmic useraccount where name='%%~G' get sid| findstr /vi "SID""') DO (
REM Strip trailing line with CR
FOR /F "delims= " %%I IN ("%%~H") DO (
REM %%I is now the SID of the USER
REG ADD "HKEY_USERS\%%I\Software\Microsoft\addstuffhere" /f
REG ADD "HKEY_USERS\%%I\Software\Microsoft\addstuffhere" /t REG_SZ /d "addstuffhere"" /f
)
)
)

batch script to exit process with error

I work for a school district and we need to remotely remove profiles. We are using RemProf. I need the script to fail if it encounters two specific domains or a device with a specific identifier in the name. I want it to exit with an error code. This will let our field staff know that they have tried to run RemProf against a device that is restricted because of domain or name. Here is what I have. The line with -SAD- identifies part of a device name. This script is not exiting if it encounters an error level of 1. It continues with RemProf and deletes profiles. I would appreciate any guidance.
Reg Query HKLM\System\CurrentControlSet\services\Tcpip\Parameters /v Hostname /f -SAD-
if %ERRORLEVEL%==1 exit /b 9
Reg Query HKLM\System\CurrentControlSet\services\Tcpip\Parameters /v Domain /f teach.inst.schools
if %ERRORLEVEL%==1 exit /b 0
Reg Query HKLM\System\CurrentControlSet\services\Tcpip\Parameters /v Domain /f admin.schools
if %ERRORLEVEL%==1 exit /b 9
Reg Query HKLM\System\CurrentControlSet\services\Tcpip\Parameters /v Domain /f elem.inst.schools
if %ERRORLEVEL%==0 goto Run_RemProf
Reg Query HKLM\System\CurrentControlSet\services\Tcpip\Parameters /v Domain /f sec.inst.schools
if %ERRORLEVEL%==0 goto Run_RemProf
:Run_RemProf
Rem Deleteing profiles and abandoned files
RemProf.exe /D: /EXCLUDE:Public,Default,Administrator,SOL
RemProf.exe /AD: /EXCLUDE:Public,Default,Administrator,SOL
Your Reg Query HKLM\System\CurrentControlSet\services\Tcpip\Parameters /v Hostname /f -SAD- always returns Hostname value, along with appropriate errorlevel return value of 0 - success (or 1 - failure) regardless of data or pattern supplied in /f switch.
reg query /? is a bit short about using /V and /F switches together:
/v Queries for a specific registry key values.
If omitted, all values for the key are queried.
Argument to this switch can be optional only when specified
along with /f switch. This specifies to search in valuenames only.
/f Specifies the data or pattern to search for.
Use double quotes if a string contains spaces. Default is "*".
Another official source says about /V switch:
/v <ValueName> Specifies the registry value name that is to be
queried. If omitted, all value names for KeyName are returned.
ValueName for this parameter is optional if the /f option is
also used.
Optional? Read dictionary.com definitions for adjective optional:
common: left to one's choice; not required or mandatory;
British: possible but not compulsory; left to personal choice.
In fact, ValueName for /V parameter should be omitted if the /f option is also used (nonofficial):
To search part of the registry, use the following syntax:
REG Query HKxx\subkey [/D|/K|/V] /F "search_pattern" [/S] [/E] [/C]
Use /D to search the data (i.e. the registry values' values), /K
to search for matching key names, /V to search for matching value
names, or none of these switches to search keys, values and data.
You can:
check ERRORLEVEL from findstr command rather, or
set desired registry data to suitable environment variable and then check whether this variable contains specified substring.
Sample script (partially commented):
#ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
set "_pattern=%~1" for demonstration purposes: first line parameter
if not defined _pattern set "_pattern=-SAD-"
rem next `_KeyName` variable keeps `reg query` line length <80 chars
set "_KeyName=HKLM\System\CurrentControlSet\services\Tcpip\Parameters"
echo(
echo `findstr` approach:
Reg Query "%_KeyName%" /v Hostname | findstr /I /C:"%_pattern%" >NUL
if errorlevel 1 (
echo `Hostname` data DOES NOT CONTAIN specified string "%_pattern%"
) else (
echo `Hostname` data CONTAINS specified string "%_pattern%"
)
echo(
echo `substring` approach:
rem set `_Hostname` and `_Domain`
for /F "tokens=1,2,*" %%G in ('
Reg Query "%_KeyName%" ^| findstr /I /R "\<Domain\> \<Hostname\>"
') do set "_%%G=%%I"
call set "_auxiliary=%%_Hostname:%_pattern%=%%"
if "%_auxiliary%"=="%_Hostname%" (
echo `Hostname` data DOES NOT CONTAIN specified string "%_pattern%"
) else (
echo `Hostname` data CONTAINS specified string "%_pattern%"
)
Output:
==> D:\bat\SO\39359057.bat -SAD-
`findstr` approach:
`Hostname` data DOES NOT CONTAIN specified string "-SAD-"
`substring` approach:
`Hostname` data DOES NOT CONTAIN specified string "-SAD-"
==> D:\bat\SO\39359057.bat %computername%
`findstr` approach:
`Hostname` data CONTAINS specified string "myNewPC"
`substring` approach:
`Hostname` data CONTAINS specified string "myNewPC"
==>

Batch file: read registry hidden and showsuperhidden

I'm writing a batch file and I need to read the values Hidden and Showsuperhidden in the registry, and put them into variables i guess. I have this so far:
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced/vHidden
I'm not sure how all this works but I'm reading up on it as well.
parsing reg query result is a pain.
Here's how you can do it :
for /f "tokens=2,*" %%a in ('reg query HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced /v "Hidden" ^| findstr Hidden') do set hiddenvalue=%%b

Resources