PAM Script example using Batch scripting to update a Windows service account credential
Overview
This code example uses standard Batch scripting to update a Windows service account credential and restart the service. The way particular example will only work on a Keeper Gateway that is running on the local server. The recommended method is using the WinRM script.
Important notes:
The rotation settings of the record must disable "symbols" because of batch scripting and escaping issues with certain symbols.
The server parameter needs to be updated with the server name or IP
Note: Server hostnames should start with a double backslash
Batch Script
@echooff:: Set the server name and service name as variablesset server=\\your-serverset service=SERVICENAMEfor /f "tokens=*" %%a in ('more') doset input=%%aset base64tmp=%temp%\base64.tmpset json=%temp%\json.tmpecho %input% > %base64tmp%certutil -decode %base64tmp% %json%for /f "usebackq delims=" %%a in (`jq -r .user %json%`) doset"user=%%a"for /f "usebackq delims=" %%a in (`jq -r .newPassword %json%`) doset"newPassword=%%a"del %base64tmp%del %json%echo"Stopping..."sc"%server%"query"%service%"|find"STOPPED"iferrorlevel1 (echo"Stopping"sc"%server%" stop "%service%")echo"Waiting for service to stop"set count=1set limit=120:loopsc"%server%"query"%service%"|find"STOPPED"iferrorlevel1 (ping 127.0.0.1 -n 1>NULset /a count +=1if %count% lss %limit% goto loop)sc"%server%"query"%service%"|find"STOPPED"iferrorlevel1 (echo"Timed out"exit /b 1)echo"Service stopped, waiting 5 seconds"timeout /t 5 /nobreak >nulecho"Setting new password"sc"%server%" config "%service%" obj=%user% password="%newPassword%"if %errorlevel% neq0exit /b %errorlevel%echo"Updated, waiting 2 seconds"timeout /t 5 /nobreak >nulecho"Starting service"sc"%server%"start"%service%"if %errorlevel% neq0exit /b %errorlevel%