Awk

讀取 json 文件並在 Bash 中執行命令

  • December 13, 2019

我想阻止下載值超過“20480”的mac地址: json文件:

   {
 "client_length": 3,
 "clients": {
   "ac:07:5f:77:40:e9": {
     "id": 1,
     "ip": "192.168.5.40",
     "mac": "ac:07:5f:85:40:e9",
     "added": 1576258952,
     "active": 1576264642,
     "duration": 5711,
     "token": "4d8fd3ce",
     "state": "Authenticated",
     "downloaded": 45059,
     "avg_down_speed": 63.12,
     "uploaded": 2976,
     "avg_up_speed": 4.17
   },
   "ac:e0:10:55:2d:78": {
     "id": 2,
     "ip": "192.168.5.132",
     "mac": "ac:e0:10:12:2d:75",
     "added": 1576258985,
     "active": 1576264663,
     "duration": 5678,
     "token": "35dfa494",
     "state": "Authenticated",
     "downloaded": 18663,
     "avg_down_speed": 26.3,
     "uploaded": 4986,
     "avg_up_speed": 7.03
   },
   "58:48:44:db:ba:ba": {
     "id": 3,
     "ip": "192.168.5.93",
     "mac": "58:48:22:db:ba:be",
     "added": 1576258973,
     "active": 1576264662,
     "duration": 5690,
     "token": "139fede2",
     "state": "Authenticated",
     "downloaded": 187876,
     "avg_down_speed": 264.15,
     "uploaded": 7910,
     "avg_up_speed": 11.12
   }
 }
}

此外,這是結果,ndsctl json而且總是會改變。ndsctl 是 nodogsplash 包的一部分。我已經在 OpenWrt (BusyBox v1.28.4) 上安裝了這個包。

我的目標:

上面的 json 給了我一些資訊。根據這個文件,我想阻止ac:07:5f:77:40:e958:48:44:db:ba:ba因為它們的下載值超過了“20480”。

我需要一個 bash 腳本來為我做這件事。

阻止mac地址的命令:

ndsctl block ac:07:5f:77:40:e9

ndsctl block 58:48:44:db:ba:ba

我做了一些事情:

root@OpenWrt:~# cat test.json | grep "mac\|downloaded"
"mac":"ac:07:5f:85:40:e9",
"downloaded":45059,
"mac":"ac:e0:10:55:2d:78",
"downloaded":18663,
"mac":"58:48:44:db:ba:ba",
"downloaded":187876,

任何的想法?

對於大多數 Unices來說,有一個用於命令行的 JSON 解析器,稱為jq隨時可用(這可能必須從您的包系統中安裝)。

有了它,就可以輕鬆解析出下載次數超過20480次的條目的MAC地址。

獲取這些資訊後,您可以將它們一一傳遞給ndsctl blockusing xargs

jq -r '.clients[] | select(.downloaded > 20480).mac' file.json |
xargs -n 1 ndsctl block

這假定 JSON 文件保存在file.json.

對於給定的 JSON 文件,這將執行兩個命令

ndsctl block ac:07:5f:85:40:e9
ndsctl block 58:48:22:db:ba:be

引用自:https://unix.stackexchange.com/questions/557105