1. 程式人生 > 其它 >一天一個 Linux 命令(43):netstat 命令

一天一個 Linux 命令(43):netstat 命令

一天一個 Linux 命令(43):netstat 命令

一、簡介

Linux下的netstat命令用於顯示各種網路相關資訊,如網路連線,路由表,介面狀態 (Interface Statistics),masquerade 連線,多播成員 (Multicast Memberships) 等等。netstat是在核心中訪問網路及相關資訊的程式,它能提供TCP連線,TCP和UDP監聽,程序記憶體管理的相關報告。

從整體上看,netstat的輸出結果可以分為兩個部分:一個是Active Internet connections,稱為有源TCP連線,其中”Recv-Q”和”Send-Q”指的是接收佇列和傳送佇列。這些數字一般都應該是0。如果不是則表示軟體包正在佇列中堆積。這種情況只能在非常少的情況見到;另一個是Active UNIX domain sockets,稱為有源Unix域套介面(和網路套接字一樣,但是隻能用於本機通訊,效能可以提高一倍)。

二、格式說明

netstat [-acCeFghilMnNoprstuvVwx][-A<網路型別>][--ip]
netstat [引數]

usage: netstat [-vWeenNcCF] [<Af>] -r         netstat {-V|--version|-h|--help}
       netstat [-vWnNcaeol] [<Socket> ...]
       netstat { [-vWeenNac] -I[<Iface>] | [-veenNac] -i | [-cnNe] -M | -s [-6tuw] } [delay]

        -r, --route              display routing table
        -I, --interfaces=<Iface> display interface table for <Iface>
        -i, --interfaces         display interface table
        -g, --groups             display multicast group memberships
        -s, --statistics         display networking statistics (like SNMP)
        -M, --masquerade         display masqueraded connections

        -v, --verbose            be verbose
        -W, --wide               don't truncate IP addresses
        -n, --numeric            don't resolve names
        --numeric-hosts          don't resolve host names
        --numeric-ports          don't resolve port names
        --numeric-users          don't resolve user names
        -N, --symbolic           resolve hardware names
        -e, --extend             display other/more information
        -p, --programs           display PID/Program name for sockets
        -o, --timers             display timers
        -c, --continuous         continuous listing

        -l, --listening          display listening server sockets
        -a, --all                display all sockets (default: connected)
        -F, --fib                display Forwarding Information Base (default)
        -C, --cache              display routing cache instead of FIB
        -Z, --context            display SELinux security context for sockets

  <Socket>={-t|--tcp} {-u|--udp} {-U|--udplite} {-S|--sctp} {-w|--raw}
           {-x|--unix} --ax25 --ipx --netrom
  <AF>=Use '-6|-4' or '-A <af>' or '--<af>'; default: inet
  List of possible address families (which support routing):
    inet (DARPA Internet) inet6 (IPv6) ax25 (AMPR AX.25) 
    netrom (AMPR NET/ROM) ipx (Novell IPX) ddp (Appletalk DDP) 
    x25 (CCITT X.25) 

三、選項說明

-a或--all 顯示所有連線中的Socket。
-A<網路型別>或--<網路型別> 列出該網路型別連線中的相關地址。
-c或--continuous 持續列出網路狀態。
-C或--cache 顯示路由器配置的快取資訊。
-e或--extend 顯示網路其他相關資訊。
-F或--fib 顯示路由快取。
-g或--groups 顯示多重廣播功能群組組員名單。
-h或--help 線上幫助。
-i或--interfaces 顯示網路介面資訊表單。
-l或--listening 顯示監控中的伺服器的Socket。
-M或--masquerade 顯示偽裝的網路連線。
-n或--numeric 直接使用IP地址,而不通過域名伺服器。
-N或--netlink或--symbolic 顯示網路硬體外圍裝置的符號連線名稱。
-o或--timers 顯示計時器。
-p或--programs 顯示正在使用Socket的程式識別碼和程式名稱。
-r或--route 顯示Routing Table。
-s或--statistics 顯示網路工作資訊統計表。
-t或--tcp 顯示TCP傳輸協議的連線狀況。
-u或--udp 顯示UDP傳輸協議的連線狀況。
-v或--verbose 顯示指令執行過程。
-V或--version 顯示版本資訊。
-w或--raw 顯示RAW傳輸協議的連線狀況。
-x或--unix 此引數的效果和指定"-A unix"引數相同。
--ip或--inet 此引數的效果和指定"-A inet"引數相同。

四、命令功能

利用 netstat 指令可讓你得知整個 Linux 系統的網路情況。

五、常見用法

5.1 顯示詳細的網路

# netstat -a


netstat的輸出結果可以分為兩個部分:

一個是Active Internet connections,稱為有源TCP連線,其中"Recv-Q"和"Send-Q"指的是接收佇列和傳送佇列。這些數字一般都應該是0。如果不是則表示軟體包正在佇列中堆積。這種情況只能在非常少的情況見到。

另一個是Active UNIX domain sockets,稱為有源Unix域套介面(和網路套接字一樣,但是隻能用於本機通訊,效能可以提高一倍)。

Proto顯示連線使用的協議,RefCnt表示連線到本套介面上的程序號,Types顯示套介面的型別,State顯示套介面當前的狀態,Path表示連線到套介面的其它程序使用的路徑名。
套介面型別:
-t :TCP

-u :UDP

-raw :RAW型別

--unix :UNIX域型別

--ax25 :AX25型別

--ipx :ipx型別

--netrom :netrom型別


狀態說明:
LISTEN:偵聽來自遠方的TCP埠的連線請求

SYN-SENT:再發送連線請求後等待匹配的連線請求(如果有大量這樣的狀態包,檢查是否中招了)

SYN-RECEIVED:再收到和傳送一個連線請求後等待對方對連線請求的確認(如有大量此狀態,估計被flood攻擊了)

ESTABLISHED:代表一個開啟的連線

FIN-WAIT-1:等待遠端TCP連線中斷請求,或先前的連線中斷請求的確認

FIN-WAIT-2:從遠端TCP等待連線中斷請求

CLOSE-WAIT:等待從本地使用者發來的連線中斷請求

CLOSING:等待遠端TCP對連線中斷的確認

LAST-ACK:等待原來的發向遠端TCP的連線中斷請求的確認(不是什麼好東西,此項出現,檢查是否被攻擊)

TIME-WAIT:等待足夠的時間以確保遠端TCP接收到連線中斷請求的確認

CLOSED:沒有任何連線狀態

5.2 顯示當前UDP連線

# netstat -nu

5.3 顯示當前TCP連線

netstat -nt

5.3 顯示UDP埠號的使用

# netstat -apu 
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
udp        0      0 0.0.0.0:bootpc          0.0.0.0:*                           933/dhclient        
udp        0      0 service-01:ntp          0.0.0.0:*                           663/ntpd            
udp        0      0 VM-0-15-centos:ntp      0.0.0.0:*                           663/ntpd            
udp6       0      0 service-01:ntp          [::]:*                              663/ntpd            
udp6       0      0 VM-0-15-centos:ntp      [::]:*                              663/ntpd 

5.4 顯示網絡卡列表

# netstat -i 
Kernel Interface table
Iface             MTU    RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
eth0             1500 125094783      0      0 0      135609023      0      0      0 BMRU
lo              65536 21298782      0      0 0      21298782      0      0      0 LRU

5.5 顯示組播組的關係

# netstat -g 
IPv6/IPv4 Group Memberships
Interface       RefCnt Group
--------------- ------ ---------------------
lo              1      all-systems.mcast.net
eth0            1      all-systems.mcast.net
lo              1      ff02::1
lo              1      ff01::1
eth0            1      ff02::1:ff3a:5f30
eth0            1      ff02::1
eth0            1      ff01::1

5.6 顯示網路統計資訊

# netstat -s

Ip:
    141486693 total packets received
    0 forwarded
    0 incoming packets discarded
    141486593 incoming packets delivered
    154098495 requests sent out
    48 dropped because of missing route
    82 reassemblies required
    14 packets reassembled ok
    14 fragments received ok
    82 fragments created
Icmp:
    13813314 ICMP messages received
    425 input ICMP message failed.
    InCsumErrors: 1
    ICMP input histogram:
        destination unreachable: 3239
        timeout in transit: 432
        echo requests: 13809376
        echo replies: 175
        timestamp request: 91
    13809624 ICMP messages sent
    0 ICMP messages failed
    ICMP output histogram:
        destination unreachable: 143
        echo request: 14
        echo replies: 13809376
        timestamp replies: 91
IcmpMsg:
        InType0: 175
        InType3: 3239
        InType8: 13809376
        InType11: 432
        InType13: 91
        OutType0: 13809376
        OutType3: 143
        OutType8: 14
        OutType14: 91
Tcp:
    11025992 active connections openings
    2461256 passive connection openings
    248809 failed connection attempts
    39534 connection resets received
    14 connections established
    123115503 segments received
    134149976 segments send out
    5202375 segments retransmited
    24422 bad segments received.
    302984 resets sent
    InCsumErrors: 23807
Udp:
    4252325 packets received
    143 packets to unknown port received.
    0 packet receive errors
    4252618 packets sent
    0 receive buffer errors
    0 send buffer errors
UdpLite:
TcpExt:
    288 SYN cookies sent
    1 SYN cookies received
    157837 invalid SYN cookies received
    228014 resets received for embryonic SYN_RECV sockets
    994 packets pruned from receive queue because of socket buffer overrun
    246 ICMP packets dropped because they were out-of-window
    965882 TCP sockets finished time wait in fast timer
    7253 packets rejects in established connections because of timestamp
    3912126 delayed acks sent
    522 delayed acks further delayed because of locked socket
    Quick ack mode was activated 152550 times
    3986 times the listen queue of a socket overflowed
    5811 SYNs to LISTEN sockets dropped
    984697 packets directly queued to recvmsg prequeue.
    464913 bytes directly in process context from backlog
    26707475 bytes directly received in process context from prequeue
    27708536 packet headers predicted
    5630 packets header predicted and directly queued to user
    44344525 acknowledgments not containing data payload received
    14968170 predicted acknowledgments
    153 times recovered from packet loss due to fast retransmit
    81069 times recovered from packet loss by selective acknowledgements
    918 bad SACK blocks received
    Detected reordering 1005 times using FACK
    Detected reordering 1003 times using SACK
    Detected reordering 32 times using reno fast retransmit
    Detected reordering 4401 times using time stamp
    1875 congestion windows fully recovered without slow start
    4205 congestion windows partially recovered using Hoe heuristic
    6088 congestion windows recovered without slow start by DSACK
    55385 congestion windows recovered without slow start after partial ack
    TCPLostRetransmit: 27834
    31 timeouts after reno fast retransmit
    11862 timeouts after SACK recovery
    44654 timeouts in loss state
    383435 fast retransmits
    25395 forward retransmits
    547771 retransmits in slow start
    3856050 other TCP timeouts
    TCPLossProbes: 589192
    TCPLossProbeRecovery: 284584
    30 classic Reno fast retransmits failed
    35939 SACK retransmits failed
    160352 DSACKs sent for old packets
    1155 DSACKs sent for out of order packets
    316513 DSACKs received
    4149 DSACKs for out of order packets received
    26395 connections reset due to unexpected data
    1736 connections reset due to early user close
    7726 connections aborted due to timeout
    TCPSACKDiscard: 41
    TCPDSACKIgnoredOld: 437
    TCPDSACKIgnoredNoUndo: 217313
    TCPSpuriousRTOs: 4212
    TCPSackShiftFallback: 699121
    TCPBacklogDrop: 1
    TCPReqQFullDoCookies: 288
    TCPRetransFail: 5
    TCPRcvCoalesce: 11995363
    TCPOFOQueue: 399736
    TCPOFOMerge: 1519
    TCPChallengeACK: 2475
    TCPSYNChallenge: 622
    TCPFastOpenCookieReqd: 11
    TCPSpuriousRtxHostQueues: 39326
    TCPAutoCorking: 533
    TCPFromZeroWindowAdv: 449
    TCPToZeroWindowAdv: 449
    TCPWantZeroWindowAdv: 3253
    TCPSynRetrans: 3411152
    TCPOrigDataSent: 76114506
    TCPHystartTrainDetect: 1896
    TCPHystartTrainCwnd: 74460
    TCPHystartDelayDetect: 6891
    TCPHystartDelayCwnd: 423886
    TCPACKSkippedSynRecv: 29912
    TCPACKSkippedPAWS: 1152
    TCPACKSkippedSeq: 971
    TCPACKSkippedTimeWait: 12
    TCPACKSkippedChallenge: 239
IpExt:
    InNoRoutes: 1
    InMcastPkts: 305307
    InOctets: 68437168659
    OutOctets: 92168136568
    InMcastOctets: 10991052
    InNoECTPkts: 143634491
    InECT1Pkts: 3
    InECT0Pkts: 8407
    InCEPkts: 1217

按照各個協議分別顯示其統計資料。如果我們的應用程式(如Web瀏覽器)執行速度比較慢,或者不能顯示Web頁之類的資料,那麼我們就可以用本選項來檢視一下所顯示的資訊。我們需要仔細檢視統計資料的各行,找到出錯的關鍵字,進而確定問題所在。

5.7 顯示監聽的套介面

# netstat -l

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 VM-0-15-centos:6666     0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:http            0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:https           0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:8000            0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:cslistener      0.0.0.0:*               LISTEN     
tcp6       0      0 [::]:mysql              [::]:*                  LISTEN     
udp        0      0 0.0.0.0:bootpc          0.0.0.0:*                          
udp        0      0 service-01:ntp          0.0.0.0:*                          
udp        0      0 VM-0-15-centos:ntp      0.0.0.0:*                          
udp6       0      0 service-01:ntp          [::]:*                             
udp6       0      0 VM-0-15-centos:ntp      [::]:*                             
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     13070    /var/run/lsm/ipc/simc
unix  2      [ ACC ]     STREAM     LISTENING     9486     /run/systemd/journal/stdout
unix  2      [ ACC ]     STREAM     LISTENING     12846    /run/dbus/system_bus_socket
unix  2      [ ACC ]     STREAM     LISTENING     532120   /tmp/mysql.sock
unix  2      [ ACC ]     STREAM     LISTENING     10552    /run/lvm/lvmpolld.socket
unix  2      [ ACC ]     STREAM     LISTENING     11852    /run/lvm/lvmetad.socket
unix  2      [ ACC ]     STREAM     LISTENING     13946    /var/run/lsm/ipc/sim
unix  2      [ ACC ]     STREAM     LISTENING     14462    /var/run/acpid.socket
unix  2      [ ACC ]     STREAM     LISTENING     291339499 /usr/local/qcloud/YunJing/conf/ydrpc_1
unix  2      [ ACC ]     SEQPACKET  LISTENING     11925    /run/udev/control
unix  2      [ ACC ]     STREAM     LISTENING     11719    /run/systemd/private
unix  2      [ ACC ]     STREAM     LISTENING     21457    /tmp/tmux-0/default

5.8 顯示所有已建立的有效連線

# netstat -n

5.9 顯示關於乙太網的統計資料

# netstat -e

用於顯示關於乙太網的統計資料。它列出的專案包括傳送的資料報的總位元組數、錯誤數、刪除數、資料報的數量和廣播的數量。這些統計資料既有傳送的資料報數量,也有接收的資料報數量。這個選項可以用來統計一些基本的網路流量

5.10 顯示關於路由表的資訊

# netstat -r

Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
default         gateway         0.0.0.0         UG        0 0          0 eth0
link-local      0.0.0.0         255.255.0.0     U         0 0          0 eth0
172.21.0.0      0.0.0.0         255.255.240.0   U         0 0          0 eth0

5.11 統計機器中網路連線各個狀態個數

netstat -a | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'

LISTEN 7
CLOSE_WAIT 314
ESTABLISHED 7
TIME_WAIT 5

5.12 把狀態全都取出來後使用uniq -c統計後再進行排序

netstat -nat |awk '{print $6}'|sort|uniq -c

314 CLOSE_WAIT
1 established)
12 ESTABLISHED
1 FIN_WAIT2
1 Foreign
7 LISTEN
2 SYN_RECV
3 TIME_WAIT

5.13 檢視程式執行的埠

netstat -ap | grep ssh

5.14 在 netstat 輸出中顯示 PID 和程序名稱

netstat -pt

5.15 找出執行在指定埠的程序,根據埠號查詢程序名

netstat -anpt | grep '80'

執行在埠80的程序id為13548,再通過ps命令就可以找到具體的應用程式了。

ps -aux | grep 13548