我得到一个arp -a结果,如下所示:
Albacore (192.168.1.1) at a5:5d:a1:ec:e3:52 on en0 ifscope [ethernet]
Beaufort (192.168.1.109) at 3B:EA:D2:2D:7F:06 on en0 ifscope [ethernet]我需要从它形成JSON,看起来像这样:
[
{
"ip":"192.168.1.1",
"mac":"a5:5d:a1:ec:e3:52",
"hostname":"Albacore"
},
{
"ip":"192.168.1.109",
"mac":"3B:EA:D2:2D:7F:06",
"hostname":"Beaufort"
}
]我知道,这个正则表达式可以找到主机名
^\S*这可以用来查找ips
((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)这是发送到mac地址的
([0-9a-f]{1,2}[\.:-]){5}([0-9a-f]{1,2})他们可能不是最好的,但他们应该完成我的用例的工作。
无论如何,我想不出如何把它们放在一起形成JSON。
谢谢你所有的建议。
发布于 2019-06-30 23:00:26
您的正则表达式在使用python regex时似乎无法工作,因此我对其进行了一些更改,下面是一个使用python的示例:
import re
import json
lines = ["Albacore (192.168.1.1) at a5:5d:a1:ec:e3:52 on en0 ifscope [ethernet]",
"Beaufort (192.168.1.109) at 3B:EA:D2:2D:7F:06 on en0 ifscope [ethernet]"]
json_file = open('json.txt', 'w')
json_file.write("{\n")
for line in lines:
dump = {}
dump['hostname'] = re.findall(r'^(.*?)\s', line)[0]
dump['mac'] = re.findall(ur'(?:[0-9a-fA-F]:?){12}', line)[0]
dump['ip'] = re.findall(r'[0-9]+(?:\.[0-9]+){3}', line)[0]
json.dump(dump, json_file)
json_file.write(",\n")
json_file.write("}")
json_file.close()以json.txt格式输出
{
{"ip": "192.168.1.1", "mac": "a5:5d:a1:ec:e3:52", "hostname": "Albacore"},
{"ip": "192.168.1.109", "mac": "3B:EA:D2:2D:7F:06", "hostname": "Beaufort"},
}如果需要,您还可以编辑JSON数据显示,了解有关它的更多信息:https://appdividend.com/2019/04/15/how-to-convert-python-dictionary-to-json-tutorial-with-example/
发布于 2019-06-30 23:34:19
通过while循环和read逐行读取输入
while read line || [[ -n $line ]]; do
...
done检查确保我们不会对错误的输入采取行动。
通过command substitution将组件捕获到变量中
ip="$(echo "$line" | sed 's/<capture pattern>/\n/')"通过printf和parameter expansion输出文本行,并将捕获替换到您想要的位置
printf "%s\n" "\"ip\":\"${ip}\","这应该足以将一个工作脚本组合在一起。此外,如果arp的输出是可靠定义良好的,则可以避免正则表达式,只需在分隔符(这里是空格)上拆分行,并使用索引和变量扩展来实现同样的目的。
通过read将空格上的行拆分为一个数组
read -ra arr <<< "$line"通过以下方式访问array元素:
${arr[index]}ip捕获需要一些string manipulation来删除括号。通过以下方式删除它们:
ip=${arr[1]#(}
ip=${ip%)}把所有这些放在一起,你就会得到这样的东西:
#!/bin/bash
## we'll insert commas between items before inserting the next item
## rather than at the end so that we don't add a trailing comma.
## we'll need this flag to know if we're at the first insertion,
## where we won't insert a comma.
first=1
printf "%s\n" "["
while read line || [[ -n $line ]]; do
if [ $first -eq 0 ]; then
printf "%s\n" ","
else
first=0
fi
read -ra arr <<< "$line"
ip=${arr[1]#(}
ip=${ip%)}
printf "%s\n" " {"
printf "%s\n" " \"ip\":\"${ip}\","
printf "%s\n" " \"mac\":\"${arr[3]}\","
printf "%s\n" " \"hostname\":\"${arr[0]}\""
printf "%s" " }"
done
printf "\n%s\n" "]"我不熟悉arp,但是如果这个文件被命名为arp-to-json,那么你可能会通过:
arp -a | arp-to-json您可以使用jq快速检查json是否格式正确
arp -a | arp-to-json | jq --indent 4预期输出应与您指定的精确匹配。
https://stackoverflow.com/questions/56825503
复制相似问题