Linux一句話命令技巧
說明:通過一句話快速理解bash/sed/awk等小工具的組合,能快速處理日常工作.
一、網站連接狀態篇:
1.查看TCP連接狀態
netstat -nat |awk ‘{print $6}’|sort|uniq -c|sort -rn
netstat -n | awk ‘/^tcp/ {++S[$NF]};END {for(a in S) print a, S[a]}’ 或
netstat -n | awk ‘/^tcp/ {++state[$NF]}; END {for(key in state) print key,”\t”,state[key]}’
netstat -n | awk ‘/^tcp/ {++arr[$NF]};END {for(k in arr) print k,”\t”,arr[k]}’
netstat -n |awk ‘/^tcp/ {print $NF}’|sort|uniq -c|sort -rn
netstat -ant | awk ‘{print $NF}’ | grep -v ‘[a-z]‘ | sort | uniq -c
(以上每一行實現的效果基本相同,在此列出不同的寫法,方便對腳本寫法的更深理解)
2.查找請求數前20個IP(常用於查找***來源):
netstat -anlp|grep 80|grep tcp|awk ‘{print $5}’|awk -F: ‘{print $1}’|sort|uniq -c|sort -nr|head -n20
netstat -ant |awk ‘/:80/{split($5,ip,”:”);++A[ip[1]]}END{for(i in A) print A[i],i}’ |sort -rn|head –n20
3.用tcpdump嗅探80端口的訪問看看誰最高
tcpdump -i eth0 -tnn dst port 80 -c 1000 | awk -F”.” ‘{print $1″.”$2″.”$3″.”$4}’ | sort | uniq -c | sort -nr |head –20
4.查找較多time_wait連接
netstat -n|grep TIME_WAIT|awk ‘{print $5}’|sort|uniq -c|sort -rn|head –n20
5.找查較多的SYN連接
netstat -an | grep SYN | awk ‘{print $5}’ | awk -F: ‘{print $1}’ | sort | uniq -c | sort -nr | more
6.根據端口列進程
netstat -ntlp | grep 80 | awk ‘{print $7}’ | cut -d/ -f1
7.查看有多少個PHP-CGI進程活動
netstat -anp | grep php-cgi | grep ^tcp | wc -l
8.查看PHP-CGI佔用內存的總數:
total=0; for i in `ps -C php-cgi -o rss=`; do total=$(($total+$i)); done; echo “PHP-CGI Memory usage: $total kb”
二、網站日誌分析篇
以apache access.log實例篇:
1.獲得訪問前10位的ip地址
cat access.log|awk ‘{print $1}’|sort|uniq -c|sort -nr|head -10
cat access.log|awk ‘{counts[$(11)]+=1}; END {for(url in counts) print counts[url], url}’
2.訪問次數最多的文件或頁面,取前20
cat access.log|awk ‘{print $11}’|sort|uniq -c|sort -nr|head -20
3.列出傳輸最大的幾個exe文件(分析下載站的時候常用)
cat access.log |awk ‘($7~/\.exe/){print $10 ” ” $1 ” ” $4 ” ” $7}’|sort -nr|head -20
4.列出輸出大於200000byte(約200kb)的exe文件以及對應文件發生次數
cat access.log |awk ‘($10 > 200000 && $7~/\.exe/){print $7}’|sort -n|uniq -c|sort -nr|head -100
5.如果日誌最後一列記錄的是頁面文件傳輸時間,則有列出到客戶端最耗時的頁面
cat access.log |awk ‘($7~/\.php/){print $NF ” ” $1 ” ” $4 ” ” $7}’|sort -nr|head -100
6.列出最最耗時的頁面(超過60秒的)的以及對應頁面發生次數
cat access.log |awk ‘($NF > 60 && $7~/\.php/){print $7}’|sort -n|uniq -c|sort -nr|head -100
7.列出傳輸時間超過 30 秒的文件
cat access.log |awk ‘($NF > 30){print $7}’|sort -n|uniq -c|sort -nr|head -20
8.統計網站流量(G)
cat access.log |awk ‘{sum+=$10} END {print sum/1024/1024/1024}’
9.統計404的連接
awk ‘($9 ~/404/)’ access.log | awk ‘{print $9,$7}’ | sort
10. 統計http status
cat access.log |awk ‘{counts[$(9)]+=1}; END {for(code in counts) print code, counts[code]}'
cat access.log |awk '{print $9}'|sort|uniq -c|sort -rn
11.蜘蛛分析
查看是哪些蜘蛛在抓取內容。
/usr/sbin/tcpdump -i eth0 -l -s 0 -w - dst port 80 | strings | grep -i user-agent | grep -i -E 'bot|crawler|slurp|spider'
以Squid access.log實例篇。
1.按域統計流量
zcat squid_access.log.tar.gz| awk '{print $10,$7}' |awk 'BEGIN{FS="[ /]"}{trfc[$4]+=$1}END{for(domain in trfc){printf "%s\t%d\n",domain,trfc[domain]}}'
效率更高的perl版本請到此下載:http://docs.linuxtone.org/soft/tools/tr.pl
2.CDN常用測試命令:
1)測試網站是否壓縮:
curl -I http://xxxxxx -H Accept-Encoding:gzip,defalte
curl -I --compressed http://xxxxx
wget -S --header="accept-encoding: gzip" http://xxxxx
2)測試某個源服務是否正常:
如:要測試http://xxxxx/kf.html 是否正常其對應的真實源服務ip(61.160.248.176).
curl --connect-timeout 5 -k -D- -o/dev/null -H "host: www.game5.com" http://xxxxxx/kf.html
curl --connect-timeout 5 -w -k -D- -o/dev/null -H "host: xianyu.game5.com"http://xxxxxx/upload/2010/08/12/shoujieqisucanglong.jpg
三、數據庫篇
1.查看數據庫執行的sql
/usr/sbin/tcpdump -i eth0 -s 0 -l -w - dst port 3306 | strings | egrep -i 'SELECT|UPDATE|DELETE|INSERT|SET|COMMIT|ROLLBACK|CREATE|DROP|ALTER|CALL'
tcpdump_mysql.sh
#!/bin/bash tcpdump -i eth0 -s 0 -l -w - dst port 3306 | strings | perl -e ' while(<>) { chomp; next if /^[^ ]+[ ]*$/; if(/^(SELECT|UPDATE|DELETE|INSERT|SET|COMMIT|ROLLBACK|CREATE|DROP|ALTER|CALL)/i) { if (defined $q) { print "$q\n"; } $q=$_; } else { $_ =~ s/^[ \t]+//; $q.=" $_"; } }'
四.系統狀態分析
1.查看網絡流量
sar -n 'DEV' 1 10000000|awk 'BEGIN{printf "DEVICE\tIN\t\tOUT\n"}''/eth0/ {printf $3" ";printf $6*8/1024/1024"Mbps ";print $7*8/1024/1024"Mbps"}'
2.查看佔用磁盤IO最多的進程。
wget -c http://linux.web.psi.ch/dist/scientific/5/gfa/all/dstat-0.6.7-1.rf.noarch.rpm dstat -M topio -d -M topbio
3.iostat -x 1 10
如果 %util 接近 100%,說明產生的I/O請求太多,I/O系統已經滿負荷,該磁盤可能存在瓶頸。
idle小於70% IO壓力就較大了,一般讀取速度有較多的wait.
svctm < await (因爲同時等待的請求的等待時間被重複計算了),
svctm的大小一般和磁盤性能有關:CPU/內存的負荷也會對其有影響,請求過多也會間接導致 svctm 的增加。
await: await的大小一般取決於服務時間(svctm) 以及 I/O 隊列的長度和 I/O 請求的發出模式。
如果 svctm 比較接近 await,說明I/O 幾乎沒有等待時間;
如果 await 遠大於 svctm,說明 I/O隊列太長,應用得到的響應時間變慢,
如果響應時間超過了用戶可以容許的範圍,這時可以考慮更換更快的磁盤,調整內核 elevator算法,優化應用,或者升級 CPU。
隊列長度(avgqu-sz)也可作爲衡量系統 I/O 負荷的指標,但由於 avgqu-sz 是按照單位時間的平均值,所以不能反映瞬間的 I/O 洪水。
vmstat 1 5
r經常大於 3-4 ,且id經常少於50,表cpu的負荷很重。
pi,po 長期不等於0,表示內存不足。
disk 經常不等於0, 且在 b中的隊列大於2-3, 表示 io性能不好。
Procs r: 運行的進程比較多,系統很繁忙
Io bo: 磁盤寫的數據量稍大
Cpu us: 持續大於50-60,服務高峯期可以接受
Cpu wa: 稍微有些高
Cpu id:持續小於50,服務高峯期可以接受
4.分析CPU的幾個命令:
mpstat -P ALL
sar -u -P ALL 2 5
sar -u 2 10
iostat -xtc 2
5.系統日誌
# cat /var/log/rflogview/*errors
檢查是否有異常錯誤記錄 也可以搜尋一些異常關鍵字,例如:
# grep -i error /var/log/messages
# grep -i fail /var/log/messages
# egrep -i 'error|warn' /var/log/messages 查看系統異常
核心日誌 # dmesg
檢查是否有異常錯誤記錄
6.關於ARP
清除所有arp緩存
arp -n|awk '/^[1-9]/ {print "arp -d "$1}'|sh
綁定已知機器的arp地址
cat /proc/net/arp | awk '{print $1 " " $4}' |sort -t. -n +3 -4 > /etc/ethers
五、硬件篇:
內存識別:
#內存大小
# dmidecode|grep -P -A5 "Memory\s+Device"|grep Size|grep -v Range
Size: 2048 MB
Size: No Module Installed
#最大內存容量
# dmidecode|grep -P 'Maximum\s+Capacity'
Maximum Capacity: 4 GB
#內存頻率
# dmidecode|grep -A16 "Memory Device"|grep Speed
Speed: 800 MHz (1.2 ns)
Speed: Unknown
CPU 識別:
①物理cpu個數:
# cat /proc/cpuinfo | grep "physical id" | sort | uniq | wc -l
②每個物理cpu中core的個數(即核數)
# cat /proc/cpuinfo | grep "cpu cores" | uniq
cpu cores : 4
③每個物理cpu中邏輯cpu(可能是core、threads或both)的個數
# cat /proc/cpuinfo | grep "siblings" | uniq
siblings : 8
查看CPU主頻:
#cat /proc/cpuinfo |grep MHz|uniq
邏輯CPU,CPU型號
#cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq -c
#當前CPU運行模式,32,64位
getconf LONG_BIT
# cat /proc/cpuinfo | grep flags | grep ' lm ' | wc -l
8
(結果大於0, 說明支持64bit計算. lm指long mode, 支持lm則是64bit)
五、技巧篇
1.查找並刪除0字節文件:
find -type f -size 0 -exec rm -rf {} \;
2.查看進程
(按內存從大到小排序)
ps -e -o "%C : %p : %z : %a"|sort -k5 -nr|more
(按cpu利用率從大到小排列)
ps -e -o "%C : %p : %z : %a"|sort -nr|more
3.打印Cache裏的URL
grep -r -a jpg /data/cache/* | strings | grep "http:" | awk -F'http:' '{print "http:"$2;}'
4.sed替換
sed -i '/Root/s/no/yes/' /etc/ssh/sshd_config sed在這個文裏Root的一行,匹配Root一行,將no替換成yes.
5.如何殺掉進程
ps aux|grep 進程名|grep -v grep|awk '{print $2}'|xargs kill -9
killall -9 nginx
6.NGINX操作常用命令:
檢查語法:
/usr/local/nginx/sbin/nginx -t
殺掉進程重啓:
killall -HUP nginx (重栽配置文件)
7.顯示運行3級別開啓的服務
ls /etc/rc3.d/S* |cut -c 15-
8.如何在編寫SHELL顯示多個信息,用EOF
cat << EOF
+--------------------------------------------------------------+
| === Welcome to Tunoff services === |
+--------------------------------------------------------------+
EOF
9.利用for循環快速給mysql建立鏈接連接:
cd /usr/local/mysql/bin
for i in *
do ln /usr/local/mysql/bin/$i /usr/bin/$i
done
10.取IP地址(可以瞭解,sed,awk,cut截取字符方面的應用)
ifconfig eth0|sed -n '2p'|awk '{print $2}'|cut -c 6-30
ifconfig eth0 |grep "inet addr:" |awk '{print $2}'|cut -c 6-
ifconfig eth0 | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'
ifconfig eth0 | sed -n '/inet /{s/.*addr://;s/ .*//;p}'
ifconfig eth0 | grep "inet addr:"|awk '{print substr($2,6,30)}'
ifconfig | grep -Eo \([0-9]\{1,3\}[\.]\)\{3\}[0-9] |sed -n '1p'
perl正則實現獲取IP地址的方法:
ifconfig -a | perl -ne 'if ( m/^\s*inet (?:addr:)?([\d.]+).*?cast/ ) { print qq($1\n); exit 0; }'
11.統計一下服務器下面所有的jpg的文件的大小。
find / -name "*.jpg" -exec wc -c {} \;|awk '{print $1}'|awk '{a+=$1}END{print a}'
統計目錄下文件的大小:
du $1 --max-depth=1 | sort -n|awk '{printf "%7.2fM ----> %s\n",$1/1024,$2}'|sed 's:/.*/\([^/]\{1,\}\)$:\1:g'
統計一個目錄中的目錄個數
ls -l | awk '/^d/' | wc -l
統計一個目錄中的文件個數
ls -l | awk '/^-/' | wc -l
統計一個目錄中的全部文件數
find ./ -type f -print | wc -l
統計一個目錄中的全部子目錄數
find ./ -type d -print | wc -l
列出當前文件夾目錄的大小:
du -b --max-depth 1 | sort -nr | perl -pe 's{([0-9]+)}{sprintf"%.1f%s", $1>=2**30? ($1/2**30, "G"): $1>=2**20? ($1/2**20, "M"):$1>=2**10? ($1/2**10, "K"): ($1, "")}e'
shaw答案 :du -hs $(du -sk ./`ls -F |grep /` |sort -nr |awk '{print $NF}')
也可 以實現,不過不是特別完美。但好記。
12.sed查找並替換內容:
sed -i "s/varnish/LTCache/g" `grep "Via" -rl /usr/local/src/varnish-2.0.4`
sed -i "s/X-Varnish/X-LTCache/g" `grep "X-Varnish" -rl /usr/local/src/varnish-2.0.4`
13. 去掉第一列的行代號。
awk '{for(i=2;i<=NF;i++) if(i!=NF){printf $i" "}else{print $i} }' list
14.消除vim中的^M的幾種方法
1)dos2uninx filename
2)sed -e 's/^M//' filename
3)vim中 :s/^M//gc
4)col -bx < dosfile > newfile
5)tr -s "\r\n" "\n" < file > newfile
15.在當前目錄及子目錄下搜索所有後綴爲 .php 的文件,並且將 字符串 baidu.com 替換成 linuxtone.org
find -name *.php |xargs perl -pi -e 's|baidu.com|linuxtone.org|g';
sed -i "s/baidu.com/opendoc.com.cn/g" `grep baidu.com -rl ./`
16. 統計文件中詞語出現的頻次:
awk '{arr[$1]+=1 } END{for(i in arr){print arr[i]}}' 文件名 | sort –rn