PowerShell against Hackers

We all want our servers to be hacker-proof, but the reality is that hackers can gain access through software flaws or even just luck as seen in the frequent news of major sites being disrupted. In the worst case scenario, it is best to be notified as soon as possible of a potential breach of security.

A good second line of defence against hackers is a file monitoring script that sends email notifications of any potentially dangerous files uploaded like php, htm and asp files for example and PowerShell makes this fairly easy to implement.

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "E:\"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true

$created = Register-ObjectEvent $watcher "Created" -Action {
  $fp = $eventArgs.FullPath
  if( $fp.ToLower().Contains( ".php" ) -or $fp.ToLower().Contains( ".htm" ) ) {
    $smtp = new-object Net.Mail.SmtpClient( "127.0.0.1" )
    $smtp.Send( "sender@server.net", "receiver@server.net", "Created " + "$($eventArgs.FullPath)", "" )
  }
}
$renamed = Register-ObjectEvent $watcher "Renamed" -Action {
  if( $fp.ToLower().Contains( ".php" ) -or $fp.ToLower().Contains( ".htm" ) ) {
    $smtp = new-object Net.Mail.SmtpClient( "127.0.0.1" )
    $smtp.Send( "sender@server.net", "receiver@server.net", "Renamed " + "$($eventArgs.FullPath)", "" )
  }
}