首页 > 解决方案 > 如何过滤powershell ssh输出

问题描述

我使用PowerShell 中描述的脚本,读/写 SSH.NET 流以从我的防火墙获取信息。但是我只需要隔离 4 个值。

编辑“ test-connection1
设置vdom“ test1
设置ip 192.168.0.1 255.255.255.0
设置allowaccess ping
设置inbandwidth 10000
设置outbandwidth 10000
编辑“ test-connection2
设置vdom“ test1
设置ip 192.168.1.1 255.255.255.0
设置allowaccess ping
设置带宽10000
设置带宽10000
--
编辑“ test-connection3
设置 vdom“ test2
设置 ip 192.168.2.1 255.255.255。0
设置允许访问 ping
设置带宽10000
设置带宽10000

我只需要显示粗体值。每次“编辑”都需要创建新行。这些值可以用逗号分隔。

我需要得到以下结果

test-connection,test1,10000,10000
test-connection2,test1,10000,10000
test-connection3,test2,10000,10000

如何操作在函数中创建的输出

function ReadStream($reader)
{
    $line = $reader.ReadLine();
    while ($line -ne $null)
    {
        $line
        $line = $reader.ReadLine()
    }
}

标签: powershellsshfilter

解决方案


如果每次编辑都是可预测的,您可以执行以下操作:

switch -Regex -File edit.txt {
  '^edit "(?<edit>[^"]+)"' {$edit = $matches.edit}
  '^set vdom "(?<vdom>[^"]+)"' {$vdom = $matches.vdom}
  '^set inbandwidth (?<inb>\d+)' {$inb = $matches.inb}
  '^set outbandwidth (?<outb>\d+)' { $edit,$vdom,$inb,$matches.outb -join ","}
}

$matches是一个自动变量,包含使用-match运算符进行字符串比较的结果。每次成功匹配时都会覆盖该变量。可以使用成员访问运算符按名称访问捕获组值.。这就是您看到$matches.edit检索edit捕获组值的语法的原因。

switch语句可以使用参数逐行读取文件-File并使用参数执行正则表达式匹配-Regex

如果编辑条目的格式是可预测的,我们可以假设我们将始终按该顺序有一个editvdominbandwidthoutbandwidth行。这意味着我们可以假设我们将按该顺序进行匹配,因此edit一旦匹配就可以输出所有块outbandwidth匹配。

正则表达式(正则表达式)是每行单引号内的值。以下是使用的两种表达式的细分:

^edit "(?<edit>[^"]+)"

  • ^ 在行首断言位置
  • edit 匹配字符 edit 字面意思(不区分大小写)
  • 命名捕获组编辑 (?[^"]+)
  • 匹配列表 [^"]+ 中不存在的单个字符,这意味着不是双引号字符。
  • 量词 (+) — 匹配一次到无限次,尽可能多次,根据需要回馈(贪婪)
  • " 匹配字符 " 字面意思(区分大小写)

^set inbandwidth (?<inb>\d+)

  • ^ 在行首断言位置
  • set inbandwidth 匹配字符 set inbandwidth 字面意思(不区分大小写)
  • 命名捕获组 inb (?\d+)
  • \d+ 匹配一个数字(等于 [0-9])
  • 量词 (+) — 匹配一次到无限次,尽可能多次,根据需要回馈(贪婪)

推荐阅读