PowerShell 腳本netstat監控網絡連接情況(報警)

需求:想把netstat -na吐出來的數據統計一下,看看本地有沒有連接外網。因部分服務器不能連接外網。如果有連接外網,可能是***,需要報警。
注意:因爲netstat是cmd的命令,儘管在PowerShell下可以運行這個命令,但是吐出來的數據是沒辦法再次加工的,它不是PowerShell原生命令。
原生命令比如Get-Command,可以通過以下腳本直接得到Get-Command中的所有的Name值,但是netstat不行。
Get-Command | Export-Csv -Path c:\1\2.csv
Import-CSV -Path c:\1\2.csv | Select-Object Name
所以解決方法是把數據吐到一個CSV文件中,然後針對CSV進行加工,最後得到需要的統計信息。
經過測試,需要PowerShell3.0以上,也就是Windows Server 2012以上的版本(windows8以上也可以)。
腳本:
netstat -an |Out-File c:\1\1.csv
$files = (Get-Childitem c:\1\1.csv).pspath
$content = get-content $files | Select-Object -Skip 4
clear-content $files
add-Content $files -Value "proto,Local Address,Port1,Foreign Address,Port2,State"
foreach ($line in $content -ne "active connections" -ne " proto local address foreign address state" -ne "活動連接" -ne " 協議 本地地址 外部地址 狀態")
{
$liner = $line.Replace("[::1]","local")
$line = $liner
$liner = $line.Replace("[::]","local")
$line = $liner
$liner = $line.Replace("127.0.0.1"," local")
$line = $liner
$liner = $line.Replace("0.0.0.0"," local")
$line = $liner
$liner = $line.Replace("10.10.14.20"," local")
$line = $liner
$liner = $line.Replace("*","outside")
$line = $liner

$line = $liner -replace("\s{1,}" ,",")
$liner = $line
$line = $liner -replace(":{1,}" ," ")
$liner = $line
$liner = $line.Replace(",TCP","TCP")
$line = $liner
$liner = $line.Replace(",UDP","UDP")
$line = $liner
$line = $liner -replace("\s{1,}" ,",")
$liner = $line
add-Content $files -Value $liner
}

以上腳本創建csv文件
以下腳本觸發報警

$emailSmtpServer = "smtp.163.com"
$emailSmtpServerPort = "25"
$emailSmtpUser = "[email protected]"
$emailSmtpPass = "XXXXXXX"
$Body = "有連接外網,可能是***!"
$emailFrom = "[email protected]"
$emailTo = "[email protected]"

$content = Import-CSV -Path c:\1\1.csv | Select "Foreign Address"
foreach ($line in $content -notlike 'local' -notlike '10.10' -notlike 'outside' -notlike '220.181.12.17')
{
$line
}
if($line -ne $null)
{
$emailMessage = New-Object System.Net.Mail.MailMessage( $emailFrom , $emailTo )
$emailMessage.Subject = "有連接外網,可能是***!"
$emailMessage.Body = $Body

$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $False
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$SMTPClient.Send( $emailMessage )
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章