我有一个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