使用 awk 输出字段进行循环

使用 awk 输出字段进行循环

我的脚本的输出

grep 'Interface GigabitEthernet' * | \
sed 's/104-8-20-23.lightspeed.gnvlsc.sbcglobal.net/104.8.20.23/g' | \
sed 's/0.0.0.0: //g' | \
sed 's/.log:/ /g' | \
sed 's/Line protocol on //g' | \
sed 's/, changed state to//g' | \
awk '{print $1" "$2" "$3" "$4" "$12" "$13'} | \
sort -u -r -k 5,5 -k 4,4 | \
awk '!seen[$5]++'

104.16.7.57 Jul 5 07:19:53 GigabitEthernet3/0/5 up
104.16.7.57 Jul 5 06:42:46 GigabitEthernet3/0/41 up
104.16.7.57 Jul 5 02:01:31 GigabitEthernet3/0/34 up
104.16.7.57 Jul 5 02:02:17 GigabitEthernet3/0/33 up
104.16.7.57 Jul 5 04:52:45 GigabitEthernet3/0/28 up
104.16.7.57 Jul 5 05:39:23 GigabitEthernet3/0/26 up
104.16.7.57 Jul 5 04:21:49 GigabitEthernet3/0/22 up
104.16.7.115 Jul 5 05:23:13 GigabitEthernet2/0/9 up
104.16.7.115 Jul 5 05:16:15 GigabitEthernet2/0/8 up
104.16.7.115 Jul 5 04:04:36 GigabitEthernet2/0/7 down
104.16.7.115 Jul 5 04:00:34 GigabitEthernet2/0/6 up
104.16.7.115 Jul 5 04:00:35 GigabitEthernet2/0/5 up
104.16.7.57 Jul 5 06:33:29 GigabitEthernet2/0/25 up
104.16.7.57 Jul 5 03:37:20 GigabitEthernet2/0/24 up
104.16.7.115 Jul 5 00:31:31 GigabitEthernet2/0/20 up
104.16.7.115 Jul 5 02:34:06 GigabitEthernet2/0/2 up
104.16.7.115 Jul 5 00:30:38 GigabitEthernet2/0/19 up
104.16.7.115 Jul 5 00:30:50 GigabitEthernet2/0/18 up
104.16.7.115 Jul 5 05:04:16 GigabitEthernet2/0/10 up
104.16.21.95 Jul 5 08:13:05 GigabitEthernet1/0/6 up
104.16.21.95 Jul 5 05:51:39 GigabitEthernet1/0/47 up
104.16.21.95 Jul 5 04:00:30 GigabitEthernet1/0/45 up
104.16.21.95 Jul 5 04:00:39 GigabitEthernet1/0/44 up
104.16.21.95 Jul 5 05:00:47 GigabitEthernet1/0/43 up
104.16.7.57 Jul 5 08:13:15 GigabitEthernet1/0/40 up
104.16.7.57 Jul 5 05:00:47 GigabitEthernet1/0/3 up
104.16.21.95 Jul 5 05:29:38 GigabitEthernet1/0/28 up
104.16.7.115 Jul 5 03:12:24 GigabitEthernet1/0/27 up
104.16.21.95 Jul 5 05:52:01 GigabitEthernet1/0/25 up
104.16.21.95 Jul 5 05:52:42 GigabitEthernet1/0/24 up
104.16.7.57 Jul 5 06:51:12 GigabitEthernet1/0/13 up
104.8.20.24 Jul 5 07:32:50 GigabitEthernet1/0/12 up

我想在循环中应用 snmpwalk 命令和第一个字段的 IP 值

 snmpwalk -v1 -c public $1 1.3.6.1.2.1.1.5.0

 $ snmpwalk -v1 -c public 10.0.2.20 1.3.6.1.2.1.1.5.0
 iso.3.6.1.2.1.1.5.0 = STRING: "C3725"

将每行的结果连接起来,这样输出就是

 104.16.7.57 C3725 Jul 5 07:19:53 GigabitEthernet3/0/5 up

但我不知道该怎么做这一部分。

答案1

您可以使用现有的管道并将其放入 shell 循环中:

grep 'Interface GigabitEthernet' * \
| sed '
    s/104-8-20-23.lightspeed.gnvlsc.sbcglobal.net/104.8.20.23/g
    s/0.0.0.0: //g
    s/.log:/ /g
    s/Line protocol on //g
    s/, changed state to//g
  ' \
| awk '{print $1, $2, $3, $4, $12, $13}' \
| sort -u -r -k 5,5 -k 4,4 \
| awk '!seen[$5]++' \
| while read -r ip rest; do
    string=$(
      snmpwalk -v1 -c public "$ip" 1.3.6.1.2.1.1.5.0 \
      | awk -F '"' '{print $2}'
    )
    printf '%s %s %s\n' "$ip" "$string" "$rest"
  done

笔记:

  • 我将所有 sed 命令收集到单个 sed 调用中。
  • 所有 grep/sed/awk/sort 命令都可以写为单个 awk 命令。

相关内容