iT邦幫忙

0

Cloudflare Api 自动化脚本问题

Hi 各位大大们,
需要大家帮忙看看,我现在使用自动添加firewall IP rule 在Cloudflare里,原因是太多Rules 和有不同cloudflare账号都需要添加。我自己已经完成能够使用脚本来自动添加Rules,但有一些小问题。当我要给各自的Rules记录notes的时候出现了一些问题,应该是for loop用到不是很好。以下是我的script.

ASN_name=$(cat ASN_name.txt)
Notes=$(cat Notes.txt)

for ASN_name in $ASN_name;
do
for Notes in $Notes;
do
update=$(curl -X POST "https://api.cloudflare.com/client/v4/accounts/xxxxxxxxxx/firewall/access_rules/rules" -H "X-Auth-Email: $auth_email" -H "X-Auth-Key: $auth_key" -H "Co
ntent-Type: application/json" --data "{ "mode":"whitelist","configuration":{"target":"asn","value":"$ASN_name"},"notes":"$Notes"}")

if [[ $update != ""success": true" ]]; then
message="$ASN_name FAILED to add. DUMPING RESULTS: $update"
log "$message"
echo -e "$message"
else
message="$ASN_name successfully Added"
log "$message"
echo "$message"

fi
done
done

https://ithelp.ithome.com.tw/upload/images/20181101/20094315jWvqGYYUh0.png
https://ithelp.ithome.com.tw/upload/images/20181101/20094315jZ25tBgYqP.png
第一张图是我现有的脚本而添加的rule,能看得到重复了。
第二张图是应该要显示出来的rule。正确的。

ASN_name.txt :

AS4134
AS4837
AS9808
AS9394

Notes.txt :

Chinanet-Backbone
CHINA-UNICOM-China169-Backbone
Guangdong-Mobile-Communication-CoLtd
China-TieTong-Telecommunications-Corporation
虽然Rules已经能添加成功,但要最求完美@@。请各位提个意见。

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
weiclin
iT邦高手 4 級 ‧ 2018-11-01 15:57:10
最佳解答

這樣讀資料:

while { read asn || [[ -n "$asn" ]];} \
    && { read -u 3 note || [[ -n "$note" ]];};
do
    echo "$asn $note";
done <ASN_name.txt 3<Notes.txt

那個 || [[ -n "$asn" ]] 是要處理 read 會因為檔案最後一行不是空行就略過不讀

雖然可以加上空行就好, 但這樣寫是比較不會忘了加而出事的, 畢竟這不好除錯

joeson iT邦新手 5 級 ‧ 2018-11-02 10:36:06 檢舉

真的是谢啦~测试了~正常添加了,感谢你~
想请问下 : read -u 3 这是什么意思?上网看了看~没看懂~

weiclin iT邦高手 4 級 ‧ 2018-11-02 12:13:59 檢舉

3<Notes.txt 開了一個 fd(file descriptor), 號碼是 3
read -u 3 從 3 這個 fd 讀資料
因為 0, 1, 2 都有其他用途了, 所以從 3 開始
可參考 File_descriptor

joeson iT邦新手 5 級 ‧ 2018-11-02 17:20:04 檢舉

好的~明白了~谢谢你~

我要發表回答

立即登入回答