获取 Netstat 输出 - Server 2008 R2 上的代码失败

如何解决获取 Netstat 输出 - Server 2008 R2 上的代码失败

我对 PowerShell 和脚本编写很陌生。我被要求在一段时间内生成大量服务器上所有侦听 TCP 端口的列表,返回一个可以导入和搜索的大 csv 文件。不幸的是,其中一些仍在运行 Server 2008R2(是的,是的,我知道...)所以使用 Get-NetTCPConnection 是不可能的。我几乎必须尝试运行 NetStat 并利用它的输出。我发现了 Adam Bertram 在 2015 年编写的一个很棒的脚本,名为 Get-LocalPort.ps1,它将输出转换为正确的 Powershell 对象,看起来很理想,但它也不能在 Server 2008R2 上运行。它产生错误 Method invocation failed because [System.Object[]] doesn't contain a method named 'Trim'.,我认为它来自行 $Netstat = (netstat -anb | where {$_ -and ($_ -ne 'Active Connections')}).Trim() | Select-Object -Skip 1 | foreach {$_ -replace '\s{2,}','|'} 我不明白为什么该行适用于较新版本但不适用于 2008R2。谁能帮我调整一下,让它在旧版本的 Powershell 上运行?非常感谢。

整个脚本如下:

<#
.SYNOPSIS
    This parses the native netstat.exe's output using the command line "netstat -anb" to find
    all of the network ports in use on a local machine and all associated processes and services
.NOTES
    Created on:     2/15/2015
    Created by:     Adam Bertram
    Filename:   Get-LocalPort.ps1
.EXAMPLE
    PS> Get-LocalPort.ps1
 
    This example will find all network ports in uses on the local computer with associated
    processes and services
 
.EXAMPLE
    PS> Get-LocalPort.ps1 | Where-Object {$_.ProcessOwner -eq 'svchost.exe'}
 
    This example will find all network ports in use on the local computer that were opened
    by the svchost.exe process.
 
.EXAMPLE
    PS> Get-LocalPort.ps1 | Where-Object {$_.IPVersion -eq 'IPv4'}
 
    This example will find all network ports in use on the local computer using IPv4 only.
#>
[CmdletBinding()]
param ()
 
begin {
    Set-StrictMode -Version Latest
    $ErrorActionPreference = 'Stop'
}
 
process {
    try {
        ## Capture the output of the native netstat.exe utility
        ## Remove the top row from the result and trim off any leading or trailing spaces from each line
        ## Replace all instances of more than 1 space with a pipe symbol.  This allows easier parsing of
        ## the fields
        $Netstat = (netstat -anb | where {$_ -and ($_ -ne 'Active Connections')}).Trim() | Select-Object -Skip 1 | foreach {$_ -replace '\s{2,'|'}
 
        $i = 0
        foreach ($Line in $Netstat) { 
            ## Create the hashtable to conver to object later
            $Out = @{
                'Protocol' = ''
                'State' = ''
                'IPVersion' = ''
                'LocalAddress' = ''
                'LocalPort' = ''
                'RemoteAddress' = ''
                'RemotePort' = ''
                'ProcessOwner' = ''
                'Service' = ''
            }
            ## If the line is a port
            if ($Line -cmatch '^[A-Z]{3}\|') {
                $Cols = $Line.Split('|')
                $Out.Protocol = $Cols[0]
                ## Some ports don't have a state.  If they do,there's always 4 fields in the line
                if ($Cols.Count -eq 4) {
                    $Out.State = $Cols[3]
                }
                ## All port lines that start with a [ are IPv6
                if ($Cols[1].StartsWith('[')) {
                    $Out.IPVersion = 'IPv6'
                    $Out.LocalAddress = $Cols[1].Split(']')[0].TrimStart('[')
                    $Out.LocalPort = $Cols[1].Split(']')[1].TrimStart(':')
                    if ($Cols[2] -eq '*:*') {
                       $Out.RemoteAddress = '*'
                       $Out.RemotePort = '*'
                    } else {
                       $Out.RemoteAddress = $Cols[2].Split(']')[0].TrimStart('[')
                       $Out.RemotePort = $Cols[2].Split(']')[1].TrimStart(':')
                    }
                } else {
                    $Out.IPVersion = 'IPv4'
                    $Out.LocalAddress = $Cols[1].Split(':')[0]
                    $Out.LocalPort = $Cols[1].Split(':')[1]
                    $Out.RemoteAddress = $Cols[2].Split(':')[0]
                    $Out.RemotePort = $Cols[2].Split(':')[1]
                }
                ## Because the process owner and service are on separate lines than the port line and the number of lines between them is variable
                ## this craziness was necessary.  This line starts parsing the netstat output at the current port line and searches for all
                ## lines after that that are NOT a port line and finds the first one.  This is how many lines there are until the next port
                ## is defined.
                $LinesUntilNextPortNum = ($Netstat | Select-Object -Skip $i | Select-String -Pattern '^[A-Z]{3}\|' -NotMatch | Select-Object -First 1).LineNumber
                ## Add the current line to the number of lines until the next port definition to find the associated process owner and service name
                $NextPortLineNum = $i + $LinesUntilNextPortNum
                ## This would contain the process owner and service name
                $PortAttribs = $Netstat[($i+1)..$NextPortLineNum]
                ## The process owner is always enclosed in brackets of,if it can't find the owner,starts with 'Can'
                $Out.ProcessOwner = $PortAttribs -match '^\[.*\.exe\]|Can'
                if ($Out.ProcessOwner) {
                    ## Get rid of the brackets and pick the first index because this is an array
                    $Out.ProcessOwner = ($Out.ProcessOwner -replace '\[|\]','')[0]
                }
                ## A service is always a combination of multiple word characters at the start of the line
                if ($PortAttribs -match '^\w+$') {
                    $Out.Service = ($PortAttribs -match '^\w+$')[0]
                }
                [pscustomobject]$Out
            }
            ## Keep the counter
            $i++
        }       
    } catch {
        Write-Error "Error: $($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)"
    }
}

解决方法

您可以执行以下操作:

# skipping header
$ns = netstat -anb | Select -Skip 3
$ns | Foreach-Object {
    # Trim surrounding spaces
    $line = $_.Trim()
    # Check for lines starting with TCP
    if ($line -cmatch '^TCP') {
        # Split lines by spaces
        $p,$l,$f,$s = $line -split '\s+'
        # Output $obj if it already exists before new one is created
        if ($obj) { $obj }
        # service and process owner are blanked since they are on another line
        $obj = new-object -TypeName Psobject -Property @{
            Protocol=$p
            State=$s
            IPVersion=('IPv6','IPv4')[$l -match ':.*:']
            LocalAddress=($l -replace '[\[\]]|:[^:]+$')
            LocalPort=$l -replace '^.*:'
            RemoteAddress=($f -replace '[\[\]]|:[^:]+$')
            RemotePort=$f -replace '^.*:'
            ProcessOwner=''
            Service=''
        }
    }
    elseif ($line -cmatch '^UDP') {
        $p,$f = $line -split '\s+'
        if ($obj) { $obj }
        $obj = new-object -TypeName Psobject -Property @{
            Protocol=$p
            State=''
            IPVersion=('IPv4','IPv6')[$l -match ':.*:']
            LocalAddress=($l -replace '[\[\]]|:[^:]+$')
            LocalPort=$l -replace '^.*:'
            RemoteAddress=($f -replace '[\[\]]|:[^:]+$')
            RemotePort=$f -replace '^.*:'
            ProcessOwner=''
            Service=''
        }
    }
    # line starts with [ then it is service name
    elseif ($line -match '^\[') {
        $obj.Service = $line -replace '[\[\]]'
    }
    else {
        $obj.ProcessOwner = $line
    }
}
,

感谢 AdminOfThings,您的第一条评论是正确的。 $Netstat = netstat -anb | where {$_ -and ($_ -ne 'Active Connections')} | foreach { $_.Trim() } | Select-Object -Skip 1 | foreach {$_ -replace '\s{2,}','|'}' 行有效,但是我还必须将最后的行从 [pscustomobject]$Out 更改为 New-Object -TypeName PSObject -Property $Out 因为 [pscustomobject] 显然是 PS 3 中的另一个新事物。通过这些更改,它可以正常工作服务器 2008R2、2012R2 和 2016。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res