我有一個bash腳本,列出了在一個端口上連接的ip地址的數量。我的問題是,有大量的連接,它是緩慢的作爲便便。我認爲這是因爲使用了子殼體,但是如果不刪除腳本的其餘部分,我就會遇到問題。下面是全部腳本,因爲它是相當短的:優化Bash腳本,刪除子shell
#!/bin/bash
portnumber=80
reversedns_enabled=0
[ ! -z "${1}" ] && portnumber=${1}
[ ! -z "${2}" ] && reversedns_enabled=${2}
#this will hold all of our ip addresses extracted from netstat
ipaddresses=""
#get all of our connected ip addresses
while read line; do
ipaddress=$(echo ${line} | cut -d' ' -f5 | sed s/:[^:]*$//)
ipaddresses="${ipaddresses}${ipaddress}\n"
done < <(netstat -ano | grep -v unix | grep ESTABLISHED | grep \:${portnumber})
#remove trailing newline
ipaddresses=${ipaddresses%%??}
#output of program
finaloutput=""
#get our ip addresses sorted, uniq counted, and reverse sorted based on amount of uniq
while read line; do
if [[ ${reversedns_enabled} -eq 1 ]]; then
reversednsname=""
#we use justipaddress to do our nslookup(remove the count of uniq)
justipaddress=$(echo ${line} | cut -d' ' -f2)
reversednsstring=$(host ${justipaddress})
if echo "${reversednsstring}" | grep -q "domain name pointer"; then
reversednsname=$(echo ${reversednsstring} | grep -o "pointer .*" | cut -d' ' -f2)
else
reversednsname="reverse-dns-not-found"
fi
finaloutput="${finaloutput}${line} ${reversednsname}\n"
else
finaloutput="${finaloutput}${line}\n"
fi
done < <(echo -e ${ipaddresses} | uniq -c | sort -r)
#tabulate that sheet son
echo -e ${finaloutput} | column -t
大部分所用的時間做這個操作:echo ${line} | cut -d' ' -f5 | sed s/:[^:]*$//
什麼是內聯這產生更快的腳本的最佳方式。它需要1000多個併發用戶(這是我的基本目標,儘管應該能夠處理更多,而不用我所有的CPU),需要一秒多。
這不是一個不合理的腳本。嘗試從命令行使用'-v'選項運行到'bash' - 例如'bash -v script-name'。該選項將在讀取每行時打印出來。看看是否有任何明顯的延遲發生在屏幕上打印一行後。那將是開始在腳本中查找性能問題的地方。 – Ned
啊哈,謝謝你,我不知道-v開關。所以,問題在於我相信的子殼 - 特別是這一行:echo $ {line} |剪下-d''-f5 | sed s /:[^:] * $ // – jett
我明白@ElliottFrisch,你是對的。 – jett