我有一個這樣的命令:
/bin/netstat -an | /usr/bin/awk -vmax=100 '/tcp/{split($5,a,":"); if(a[1] > 0 && a[1]!="0.0.0.0" && a[1]!="127.0.0.1" && a[1]!="111.222.111.222" ... 50 addresses... && a[1]!="211.112.211.112"){c[a[1]] }} END{for(ip in c){if(c[ip]>max){print ip}}}' | while read ip; do /sbin/iptables -m comment --comment "SCAN BLOCK" -I INPUT 1 -s $ip -j DROP; done
問題是我怎樣才能讓它“漂亮”,也就是縮短它以從檔案中讀取 IP 地址,或者從命令上面的陣列串列中讀取 IP 地址,或者類似的東西,因為我現在有近 100 個 IP,并且所有 IP 都一個接一個大命令列。
基本上,如何制作這樣的命令:
/bin/netstat -an | /usr/bin/awk -vmax=100 '/tcp/{split($5,a,":"); if(a[1] > 0 && a[1]!="read from file"){c[a[1]] }} END{for(ip in c){if(c[ip]>max){print ip}}}' | while read ip; do /sbin/iptables -m comment --comment "SCAN BLOCK" -I INPUT 1 -s $ip -j DROP; done
提前致謝!
uj5u.com熱心網友回復:
將 ips 串列放在一個檔案中,例如:
$ cat iplist.txt
0.0.0.0
127.0.0.1
111.222.111.222
... snip ...
211.112.211.112
一般的方法是awk處理 2 個具有不同邏輯的輸入檔案,例如:
/bin/netstat -an |
/usr/bin/awk -vmax=100 '
# process 1st file (iplist.txt):
FNR==NR { iplist[$1] # FNR==NR is only true for the 1st file; for follow-on files FNR resets to 1 but NR keeps increasing
next # skip to next input record; keeps from running follow-on code against 1st file contents
}
# process 2nd file (stdin):
/tcp/ { split($5,a,":")
if (a[1] > 0 && !(a[1] in iplist))
c[a[1]]
}
END { for (ip in c)
if (c[ip]>max)
print ip
}
' iplist.txt - # 2nd file actually says to read from stdin (ie, output from netstat call)
注意:然后 OP 會將此輸出通過管道傳輸到同一while/iptables回圈,例如:
/bin/netstat -an |
/usr/bin/awk -vmax=100 '
FNR==NR { iplist[$1]
... snip ...
print ip
}
' iplist.txt - | while read ip; do /sbin/iptables ...;done
# or collapsed to one line (though harder to read and/or troubleshoot):
netstat -an | awk -vmax=100 'FNR==NR{iplist[$1];next} /tcp/{split($5,a,":"); if (a[1] > 0 && !(a[1] in iplist)) c[a[1]] } END{for (ip in c) if (c[ip]>max) print ip}' iplist.txt - | while read ip; do /sbin/iptables ...;done
uj5u.com熱心網友回復:
如果您不關心輸出順序,為什么不像iplist.txt其他人建議的那樣將 1st 讀入一個陣列,然后只要它比您的vmax閾值大 1 就輸出,例如:
# imagine the <( echo ... ) is the iplist.txt being read in jot -b '1.0.0.1' 105 | gcat -n | mawk 'FNR==NR ? __[$(_<_)] : $NF in __ && __[ $NF ] == _' \_='100' <( echo '1.0.0.1' ) -
101 1.0.0.1
ps: jot -w '%d 1.0.0.1' 105同樣適用line 1,但是第 1 行是什么并不重要,因為它代表通過管道進入的任何內容
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/503762.html
