調試排錯 - Java問題排查:Linux命令


本文原創,更多內容可以參考: Java 全棧知識體系。如需轉載請說明原處。

Java 在線問題排查主要分兩篇:本文是第一篇,通過linux常用命令排查。@pdai

文本操作

文本查找 - grep

grep常用命令:

# 基本使用
grep yoursearchkeyword f.txt     #文件查找
grep 'KeyWord otherKeyWord' f.txt cpf.txt #多文件查找, 含空格加引號
grep 'KeyWord' /home/admin -r -n #目錄下查找所有符合關鍵字的文件
grep 'keyword' /home/admin -r -n -i # -i 忽略大小寫
grep 'KeyWord' /home/admin -r -n --include *.{vm,java} #指定文件后綴
grep 'KeyWord' /home/admin -r -n --exclude *.{vm,java} #反匹配

# cat + grep
cat f.txt | grep -i keyword # 查找所有keyword且不分大小寫  
cat f.txt | grep -c 'KeyWord' # 統計Keyword次數

# seq + grep
seq 10 | grep 5 -A 3    #上匹配
seq 10 | grep 5 -B 3    #下匹配
seq 10 | grep 5 -C 3    #上下匹配,平時用這個就妥了

Grep的參數:

--color=auto:顯示顏色;
-i, --ignore-case:忽略字符大小寫;
-o, --only-matching:只顯示匹配到的部分;
-n, --line-number:顯示行號;
-v, --invert-match:反向顯示,顯示未匹配到的行;
-E, --extended-regexp:支持使用擴展的正則表達式;
-q, --quiet, --silent:靜默模式,即不輸出任何信息;
-w, --word-regexp:整行匹配整個單詞;
-c, --count:統計匹配到的行數; print a count of matching lines;

-B, --before-context=NUM:print NUM lines of leading context   后#行 
-A, --after-context=NUM:print NUM lines of trailing context   前#行 
-C, --context=NUM:print NUM lines of output context           前后各#行 

文本分析 - awk

awk基本命令:

# 基本使用
awk '{print $4,$6}' f.txt
awk '{print NR,$0}' f.txt cpf.txt    
awk '{print FNR,$0}' f.txt cpf.txt
awk '{print FNR,FILENAME,$0}' f.txt cpf.txt
awk '{print FILENAME,"NR="NR,"FNR="FNR,"$"NF"="$NF}' f.txt cpf.txt
echo 1:2:3:4 | awk -F: '{print $1,$2,$3,$4}'

# 匹配
awk '/ldb/ {print}' f.txt   #匹配ldb
awk '!/ldb/ {print}' f.txt  #不匹配ldb
awk '/ldb/ && /LISTEN/ {print}' f.txt   #匹配ldb和LISTEN
awk '$5 ~ /ldb/ {print}' f.txt #第五列匹配ldb

內建變量

`NR`: NR表示從awk開始執行后,按照記錄分隔符讀取的數據次數,默認的記錄分隔符為換行符,因此默認的就是讀取的數據行數,NR可以理解為Number of Record的縮寫。

`FNR`: 在awk處理多個輸入文件的時候,在處理完第一個文件后,NR並不會從1開始,而是繼續累加,因此就出現了FNR,每當處理一個新文件的時候,FNR就從1開始計數,FNR可以理解為File Number of Record。

`NF`: NF表示目前的記錄被分割的字段的數目,NF可以理解為Number of Field。

更多請參考:Linux awk 命令

文本處理 - sed

sed常用:

# 文本打印
sed -n '3p' xxx.log #只打印第三行
sed -n '$p' xxx.log #只打印最后一行
sed -n '3,9p' xxx.log #只查看文件的第3行到第9行
sed -n -e '3,9p' -e '=' xxx.log #打印3-9行,並顯示行號
sed -n '/root/p' xxx.log #顯示包含root的行
sed -n '/hhh/,/omc/p' xxx.log # 顯示包含"hhh"的行到包含"omc"的行之間的行

# 文本替換
sed -i 's/root/world/g' xxx.log # 用world 替換xxx.log文件中的root; s==search  查找並替換, g==global  全部替換, -i: implace

# 文本插入
sed '1,4i hahaha' xxx.log # 在文件第一行和第四行的每行下面添加hahaha
sed -e '1i happy' -e '$a new year' xxx.log  #【界面顯示】在文件第一行添加happy,文件結尾添加new year
sed -i -e '1i happy' -e '$a new year' xxx.log #【真實寫入文件】在文件第一行添加happy,文件結尾添加new year

# 文本刪除
sed  '3,9d' xxx.log # 刪除第3到第9行,只是不顯示而已
sed '/hhh/,/omc/d' xxx.log # 刪除包含"hhh"的行到包含"omc"的行之間的行
sed '/omc/,10d' xxx.log # 刪除包含"omc"的行到第十行的內容

# 與find結合
find . -name  "*.txt" |xargs   sed -i 's/hhhh/\hHHh/g'
find . -name  "*.txt" |xargs   sed -i 's#hhhh#hHHh#g'
find . -name  "*.txt" -exec sed -i 's/hhhh/\hHHh/g' {} \;
find . -name  "*.txt" |xargs cat

更多請參考:Linux sed 命令 或者 Linux sed命令詳解

文件操作

文件監聽 - tail

最常用的tail -f filename

# 基本使用
tail -f xxx.log # 循環監聽文件
tail -300f xxx.log #倒數300行並追蹤文件
tail +20 xxx.log #從第 20 行至文件末尾顯示文件內容

# tailf使用
tailf xxx.log #等同於tail -f -n 10 打印最后10行,然后追蹤文件

tail -f 與tail F 與tailf三者區別

`tail  -f `  等於--follow=descriptor,根據文件描述進行追蹤,當文件改名或刪除后,停止追蹤。

`tail -F` 等於 --follow=name ==retry,根據文件名字進行追蹤,當文件改名或刪除后,保持重試,當有新的文件和他同名時,繼續追蹤

`tailf` 等於tail -f -n 10(tail -f或-F默認也是打印最后10行,然后追蹤文件),與tail -f不同的是,如果文件不增長,它不會去訪問磁盤文件,所以tailf特別適合那些便攜機上跟蹤日志文件,因為它減少了磁盤訪問,可以省電。

tail的參數

-f 循環讀取
-q 不顯示處理信息
-v 顯示詳細的處理信息
-c<數目> 顯示的字節數
-n<行數> 顯示文件的尾部 n 行內容
--pid=PID 與-f合用,表示在進程ID,PID死掉之后結束
-q, --quiet, --silent 從不輸出給出文件名的首部
-s, --sleep-interval=S 與-f合用,表示在每次反復的間隔休眠S秒

文件查找 - find

sudo -u admin find /home/admin /tmp /usr -name \*.log(多個目錄去找)
find . -iname \*.txt(大小寫都匹配)
find . -type d(當前目錄下的所有子目錄)
find /usr -type l(當前目錄下所有的符號鏈接)
find /usr -type l -name "z*" -ls(符號鏈接的詳細信息 eg:inode,目錄)
find /home/admin -size +250000k(超過250000k的文件,當然+改成-就是小於了)
find /home/admin f -perm 777 -exec ls -l {} \; (按照權限查詢文件)
find /home/admin -atime -1  1天內訪問過的文件
find /home/admin -ctime -1  1天內狀態改變過的文件    
find /home/admin -mtime -1  1天內修改過的文件
find /home/admin -amin -1  1分鍾內訪問過的文件
find /home/admin -cmin -1  1分鍾內狀態改變過的文件    
find /home/admin -mmin -1  1分鍾內修改過的文件

pgm

批量查詢vm-shopbase滿足條件的日志

pgm -A -f vm-shopbase 'cat /home/admin/shopbase/logs/shopbase.log.2017-01-17|grep 2069861630'

查看網絡和進程

查看所有網絡接口的屬性

[root@pdai.tech ~]# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.31.165.194  netmask 255.255.240.0  broadcast 172.31.175.255
        ether 00:16:3e:08:c1:ea  txqueuelen 1000  (Ethernet)
        RX packets 21213152  bytes 2812084823 (2.6 GiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 25264438  bytes 46566724676 (43.3 GiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 502  bytes 86350 (84.3 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 502  bytes 86350 (84.3 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

查看防火牆設置

[root@pdai.tech ~]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

查看路由表

[root@pdai.tech ~]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         172.31.175.253  0.0.0.0         UG    0      0        0 eth0
169.254.0.0     0.0.0.0         255.255.0.0     U     1002   0        0 eth0
172.31.160.0    0.0.0.0         255.255.240.0   U     0      0        0 eth0

netstat

查看所有監聽端口

[root@pdai.tech ~]# netstat -lntp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name  
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      970/nginx: master p
tcp        0      0 0.0.0.0:9999            0.0.0.0:*               LISTEN      1249/java         
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      970/nginx: master p
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1547/sshd         
tcp6       0      0 :::3306                 :::*                    LISTEN      1894/mysqld       

查看所有已經建立的連接

[root@pdai.tech ~]# netstat -antp
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      970/nginx: master p
tcp        0      0 0.0.0.0:9999            0.0.0.0:*               LISTEN      1249/java
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      970/nginx: master p
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1547/sshd
tcp        0      0 172.31.165.194:53874    100.100.30.25:80        ESTABLISHED 18041/AliYunDun
tcp        0     64 172.31.165.194:22       xxx.194.1.200:2649      ESTABLISHED 32516/sshd: root@pt
tcp6       0      0 :::3306                 :::*                    LISTEN      1894/m

查看當前連接

[root@pdai.tech ~]# netstat -nat|awk  '{print $6}'|sort|uniq -c|sort -rn
      5 LISTEN
      2 ESTABLISHED
      1 Foreign
      1 established)

查看網絡統計信息進程

[root@pdai.tech ~]# netstat -s
Ip:
    21017132 total packets received
    0 forwarded
    0 incoming packets discarded
    21017131 incoming packets delivered
    25114367 requests sent out
    324 dropped because of missing route
Icmp:
    18088 ICMP messages received
    692 input ICMP message failed.
    ICMP input histogram:
        destination unreachable: 4241
        timeout in transit: 19
        echo requests: 13791
        echo replies: 4
        timestamp request: 33
    13825 ICMP messages sent
    0 ICMP messages failed
    ICMP output histogram:
        destination unreachable: 1
        echo replies: 13791
        timestamp replies: 33
IcmpMsg:
        InType0: 4
        InType3: 4241
        InType8: 13791
        InType11: 19
        InType13: 33
        OutType0: 13791
        OutType3: 1
        OutType14: 33
Tcp:
    12210 active connections openings
    208820 passive connection openings
    54198 failed connection attempts
    9805 connection resets received
...

netstat 請參考這篇文章: Linux netstat命令詳解

查看所有進程

[root@pdai.tech ~]# ps -ef | grep java
root      1249     1  0 Nov04 ?        00:58:05 java -jar /opt/tech_doc/bin/tech_arch-0.0.1-RELEASE.jar --server.port=9999
root     32718 32518  0 08:36 pts/0    00:00:00 grep --color=auto java

top

top除了看一些基本信息之外,剩下的就是配合來查詢vm的各種問題了

# top -H -p pid
top - 08:37:51 up 45 days, 18:45,  1 user,  load average: 0.01, 0.03, 0.05
Threads:  28 total,   0 running,  28 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.7 us,  0.7 sy,  0.0 ni, 98.6 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  1882088 total,    74608 free,   202228 used,  1605252 buff/cache
KiB Swap:  2097148 total,  1835392 free,   261756 used.  1502036 avail Mem

  PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND
 1347 root      20   0 2553808 113752   1024 S  0.3  6.0  48:46.74 VM Periodic Tas
 1249 root      20   0 2553808 113752   1024 S  0.0  6.0   0:00.00 java
 1289 root      20   0 2553808 113752   1024 S  0.0  6.0   0:03.74 java
...

查看磁盤和內存相關

查看內存使用 - free -m

[root@pdai.tech ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:           1837         196         824           0         816        1469
Swap:          2047         255        1792

查看各分區使用情況

[root@pdai.tech ~]# df -h
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        909M     0  909M   0% /dev
tmpfs           919M     0  919M   0% /dev/shm
tmpfs           919M  452K  919M   1% /run
tmpfs           919M     0  919M   0% /sys/fs/cgroup
/dev/vda1        40G   15G   23G  40% /
tmpfs           184M     0  184M   0% /run/user/0

查看指定目錄的大小

[root@pdai.tech ~]# du -sh
803M

查看內存總量

[root@pdai.tech ~]# grep MemTotal /proc/meminfo
MemTotal:        1882088 kB

查看空閑內存量

[root@pdai.tech ~]# grep MemFree /proc/meminfo
MemFree:           74120 kB

查看系統負載磁盤和分區

[root@pdai.tech ~]# grep MemFree /proc/meminfo
MemFree:           74120 kB

查看系統負載磁盤和分區

[root@pdai.tech ~]# cat /proc/loadavg
0.01 0.04 0.05 2/174 32751

查看掛接的分區狀態

[root@pdai.tech ~]# mount | column -t
sysfs       on  /sys                             type  sysfs       (rw,nosuid,nodev,noexec,relatime)
proc        on  /proc                            type  proc        (rw,nosuid,nodev,noexec,relatime)
devtmpfs    on  /dev                             type  devtmpfs    (rw,nosuid,size=930732k,nr_inodes=232683,mode=755)
securityfs  on  /sys/kernel/security             type  securityfs  (rw,nosuid,nodev,noexec,relatime)
...

查看所有分區

[root@pdai.tech ~]# fdisk -l

Disk /dev/vda: 42.9 GB, 42949672960 bytes, 83886080 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x0008d73a

   Device Boot      Start         End      Blocks   Id  System
/dev/vda1   *        2048    83884031    41940992   83  Linux

查看所有交換分區

[root@pdai.tech ~]# swapon -s
Filename                                Type            Size    Used    Priority
/etc/swap                               file    2097148 261756  -2

查看硬盤大小

[root@pdai.tech ~]# fdisk -l |grep Disk
Disk /dev/vda: 42.9 GB, 42949672960 bytes, 83886080 sectors
Disk label type: dos
Disk identifier: 0x0008d73a

查看用戶和組相關

查看活動用戶

[root@pdai.tech ~]# w
 08:47:20 up 45 days, 18:54,  1 user,  load average: 0.01, 0.03, 0.05
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/0    xxx.194.1.200    08:32    0.00s  0.32s  0.32s -bash

查看指定用戶信息

[root@pdai.tech ~]# id
uid=0(root) gid=0(root) groups=0(root)

查看用戶登錄日志

[root@pdai.tech ~]# last
root     pts/0        xxx.194.1.200    Fri Dec 20 08:32   still logged in
root     pts/0        xxx.73.164.60     Thu Dec 19 21:47 - 00:28  (02:41)
root     pts/0        xxx.106.236.255  Thu Dec 19 16:00 - 18:24  (02:23)
root     pts/1        xxx.194.3.173    Tue Dec 17 13:35 - 17:37  (04:01)
root     pts/0        xxx.194.3.173    Tue Dec 17 13:35 - 17:37  (04:02)
...

查看系統所有用戶

[root@pdai.tech ~]# cut -d: -f1 /etc/passwd
root
bin
daemon
adm
...

查看系統所有組

cut -d: -f1 /etc/group

查看服務,模塊和包相關

# 查看當前用戶的計划任務服務
crontab -l 

# 列出所有系統服務
chkconfig –list 

# 列出所有啟動的系統服務程序
chkconfig –list | grep on 

# 查看所有安裝的軟件包
rpm -qa 

# 列出加載的內核模塊
lsmod 

查看系統,設備,環境信息

# 常用
env # 查看環境變量資源
uptime # 查看系統運行時間、用戶數、負載
lsusb -tv # 列出所有USB設備的linux系統信息命令
lspci -tv # 列出所有PCI設備
head -n 1 /etc/issue # 查看操作系統版本,是數字1不是字母L
uname -a # 查看內核/操作系統/CPU信息的linux系統信息命令

# /proc/
cat /proc/cpuinfo :查看CPU相關參數的linux系統命令
cat /proc/partitions :查看linux硬盤和分區信息的系統信息命令
cat /proc/meminfo :查看linux系統內存信息的linux系統命令
cat /proc/version :查看版本,類似uname -r
cat /proc/ioports :查看設備io端口
cat /proc/interrupts :查看中斷
cat /proc/pci :查看pci設備的信息
cat /proc/swaps :查看所有swap分區的信息
cat /proc/cpuinfo |grep "model name" && cat /proc/cpuinfo |grep "physical id"

tsar

tsar是淘寶開源的的采集工具。很好用, 將歷史收集到的數據持久化在磁盤上,所以我們快速來查詢歷史的系統數據。當然實時的應用情況也是可以查詢的啦。大部分機器上都有安裝。

tsar  ##可以查看最近一天的各項指標
tsar --live ##可以查看實時指標,默認五秒一刷
tsar -d 20161218 ##指定查看某天的數據,貌似最多只能看四個月的數據
tsar --mem
tsar --load
tsar --cpu ##當然這個也可以和-d參數配合來查詢某天的單個指標的情況 

具體可以看這篇文章:linux 淘寶開源監控工具tsar

更多內容

最全的Java后端知識體系 https://www.pdai.tech, 每天更新中...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM