Question

I have a deployment script (.bat), part of which requires calling other programs and sending a password on the command line. I log the output of the deployment script to a file. The problem is that the password gets logged as well. I need a way of sanitizing this log file.

One way to do this is to not echo the line which contains the password, but I would prefer to just replace the password with another string.

This is done on a server (Windows 2008), so I can't just install cygwin or the like. I thought the Windows 'find' command may help, but the best it can do is omit the whole line with the '/v' option.

UPD: Did some research, and I think PowerShell is the way to go. The password is in the environment variable, so need need to figure out how to get read it and replace.

Was it helpful?

Solution 2

I perused the PowerShell option and after getting past the encoding, quotes and a few other issues, here is my final solution:

powershell "& {(Get-Content $env:LOG_FILENAME)|Foreach-Object {$_ -replace [regex]::escape($env:PASSWORD), '######'} | Set-Content ($env:LOG_FILENAME+\".clean.\"+(get-date).toString('yyyyMMddhhmmss')+\".log\")}"

This line is called from a batch file, as the last step of the deployment script. Earlier in the script the values for LOG_FILENAME and PASSWORD are set.

Breaking it down:

Executing a PowerShell from a batch file:

powershell "& {...}"

Reading in the log file:

(Get-Content $env:LOG_FILENAME)

For each line, replace [regex]::escape($env:PASSWORD) with '######':

Foreach-Object {$_ -replace [regex]::escape($env:PASSWORD), '######'}

Escape any characters in the PASSWORD environment variable which may be interpreted as regex reserved character:

[regex]::escape($env:PASSWORD)

Save the output to a new log file with a .clean.[timestamp].log appended to the original name:

Set-Content ($env:LOG_FILENAME+\".clean.\"+(get-date).toString('yyyyMMddhhmmss')+\".log\")

OTHER TIPS

If you can use JavaScript, something like the following should do it:

var rePassword = /password=\S+/g;
while (!WScript.StdIn.AtEndOfStream)
{
  WScript.StdOut.WriteLine(WScript.StdIn.ReadLine().replace(rePassword, 'password=sanitized'));
}

That will read its standard input, replace any occurrences of the string "password=" followed by any number of non-whitespace characters with the string "password=sanitized and write the results to standard output. You can tweak the rePassword regular expression and the replacement string to suit your requirements. Assuming you saved that script as "sanitize.js", you could run it from a batch script as follows:

cscript sanitize.js < logfile.log > logfile.sanitized
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top