温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用PowerShell脚本netstat监控网络连接情况

发布时间:2021-09-26 15:58:39 来源:亿速云 阅读:331 作者:柒染 栏目:系统运维

这期内容当中小编将会给大家带来有关如何使用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 = "normanjin@163.com"
$emailSmtpPass = "XXXXXXX"
$Body = "有连接外网,可能是***!"
$emailFrom = "normanjin@163.com"
$emailTo = "normanjin@163.com"

$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 )
}

上述就是小编为大家分享的如何使用PowerShell脚本netstat监控网络连接情况了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI