在 Bash 中解析 SNMP 输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18586576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:26:21  来源:igfitidea点击:

Parse SNMP output in Bash

linuxbash

提问by Kareem Hamed

I need to process the text output from the below command:

我需要处理以下命令的文本输出:

snmpwalk -v2c -c community 192.168.122.15 .1.3.6.1.4.1.14823.2.2.1.4.1.2.1.39

The Original output is:

原始输出是:

SNMPv2-SMI::enterprises.14823.2.2.1.4.1.2.1.39.252.200.151.233.54.69.197.39.5.77 = STRING: "Android"

SNMPv2-SMI::enterprises.14823.2.2.1.4.1.2.1.39.252.200.151.233.54.69.197.39.5.77 = STRING: "Android"

I need the output to look like

我需要输出看起来像

197.39.5.77="Android"

197.39.5.77is the last four digits before the =sign.

197.39.5.77=符号前的最后四位数字。

回答by tripleee

If the prefix is completely static, just remove it.

如果前缀是完全静态的,只需将其删除。

result=$(snmpwalk -v2c -c community 192.168.122.15 .1.3.6.1.4.1.14823.2.2.1.4.1.2.1.39)
result=${result#'SNMPv2-SMI::enterprises.14823.2.2.1.4.1.2.1.39.252.200.151.233.54.69.'}
echo "${result/ = STRING: /}"

Or you could do

或者你可以做

oldIFS=$IFS
IFS=' .'
set $($(snmpwalk -v2c -c community 192.168.122.15 .1.3.6.1.4.1.14823.2.2.1.4.1.2.1.39)
IFS=$oldIFS
shift 16
result="...="

The numeric argument to shiftand the ${var/str/subst}construct are Bashisms.

shift${var/str/subst}构造的数字参数是 Bashisms。

回答by jxh

With sed:

sed

snmpwalk -v2c -c community 192.168.122.15 .1.3.6.1.4.1.14823.2.2.1.4.1.2.1.39 \
| sed -e 's/.*\.\([0-9]\+\(\.[0-9]\+\)\{3\}\).*\(".*"\)/=/'

Or with bashproper:

bash适当的:

snmpwalk -v2c -c community 192.168.122.15 .1.3.6.1.4.1.14823.2.2.1.4.1.2.1.39 \
| while read a b c; do echo ${a#${a%*.*.*.*.*}.}=\"${c#*\"}; done

回答by dogbane

Pipe through sedas shown below:

管道sed如下图所示:

$ snmpwalk -v2c -c community 192.168.122.15 .1.3.6.1.4.1.14823.2.2.1.4.1.2.1.39 | sed -r 's/.*\.([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+) = .*: (.*)/=/g'
197.39.5.77="Android"

回答by Bentoy13

Try grep -Eo '(\.[0-9]{1,3}){4}\s*=.*$' | sed -r 'sed -r 's/\s*=[^:]+:/=/;s/^\.//'

尝试 grep -Eo '(\.[0-9]{1,3}){4}\s*=.*$' | sed -r 'sed -r 's/\s*=[^:]+:/=/;s/^\.//'

First part is to isolate the end of the line with a good address followed with =; the second part with sederases any string between =and :, and erases also the first dot before IPv4 address. For compactness, grepis searching for 4 times a dot followed with at most 3 digits.

第一部分是用一个好的地址来隔离行尾,然后是=; 第二部分 withsed擦除=和之间的任何字符串:,并擦除 IPv4 地址之前的第一个点。为了紧凑,grep正在搜索 4 次一个点,后跟最多 3 位数字。