Search code examples
powershellloggingtor

Check log file for access from Tor exit nodes


I am trying to write a script that will download the current Tor exit node list and check a local log file for access from Tor.

The code below outputs matches from Tor IPs in the log file to the console, but I would like to output the Select-String output in the foreach loop to a file (in addition to writing it to the console).

Once I have the results output to a file, I'll need to check the results to see if there was a match.

Any tips on how to output the foreach Select-String to a file and how to check for matches would be appreciated.

$source = "https://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=[serverip]&port=[port]"
$dest = "C:\tor.txt"
$wc = New-Object System.Net.WebClient
$wc.DownloadFile($source, $dest)
Get-Content "C:\tor.txt" | where { $_ -notmatch "^#" } | Set-Content "C:\filteredtor.txt"
Remove-Item "C:\tor.txt"
$list = get-content "C:\filteredtor.txt"
ForEach ($_ in $list) {Select-String "C:\logfile.log" -pattern $_}

Solution

  • The Tee-Object cmdlet will save a copy of the input stream to a file while passing it to the output stream. Also, by using DownloadString() instead of DownloadFile() you could streamline your code to a single pipeline and remove the need for temporary files:

    $source  = 'https://...'
    $log     = 'C:\logfile.log'
    $results = 'C:\results.txt'
    
    $wc = New-Object System.Net.WebClient
    ($wc.DownloadString($source)) -split "`n" | ? { $_ -notmatch '^(#|\s*$)' } | % {
      Select-String $log -pattern $_ | Tee-Object $results -Append
    }
    
    if ((Test-Path -LiteralPath $results) -and (Get-Content $results)) {
      # do something
    }