Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

每天一個 Linux 命令(51):ss 命令詳解

ss 命令用來顯示處於活動狀態的 socket 資訊。

用法與功能

用法:ss [參數]
     ss [參數] [過濾條件]

ss 與 netstat 類似,都能查看網路狀態,包括 TCP、UDP 連線與埠號。但 ss 的優勢在於能顯示更多、更細節的 TCP 與連線狀態資訊,而且比 netstat 更快速。

當伺服器的 socket 連線數變大時,不論用 netstat 還是直接 cat /proc/net/tcp,速度都會很慢。連線數上萬的時候,用 netstat 等於浪費生命,用 ss 才是節省時間。ss 快的秘訣是它用到了 TCP 協定堆疊中的 tcp_diag 模組,能直接拿到 Linux 核心的第一手資訊;即使系統沒有 tcp_diag,ss 仍可正常運行,只是效率稍差。

常用選項

-t, --tcp       只顯示 TCP socket
-u, --udp       只顯示 UDP socket
-d, --dccp      只顯示 DCCP socket
-w, --raw       只顯示 RAW socket
-x, --unix      只顯示 Unix socket
-a, --all       顯示所有 socket
-l              只顯示 LISTEN 狀態(連接打開)
-s, --summary   顯示 socket 使用概況
-p, --processes  顯示使用 socket 的進程

實例

1. 顯示 TCP 連線

[root@localhost sunjimeng]# ss -t -a
State      Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN     0      128    *:ssh            *:*
LISTEN     0      128    127.0.0.1:ipp    *:*
LISTEN     0      100    127.0.0.1:smtp   *:*
TIME-WAIT  0      0      192.168.142.128:52859 115.28.122.210:http
LISTEN     0      128    :::ssh          :::*
LISTEN     0      100    ::1:smtp        ::::*

對照 netstat 的輸出可見,ss 的欄位更精簡,資訊也更集中。

2. 顯示 socket 使用概況

[root@localhost sunjimeng]# ss -s
Total: 1133 (kernel 1377)
TCP: 7 (estab 0, closed 1, orphaned 0, synrecv 0, timewait 0/0), ports 0
Transport Total IP IPv6
*         1377  -  -
RAW          1   0   1
UDP          9   6   3
TCP          6   3   3
INET        16   9   7
FRAG         0   0   0

3. 列出所有打開的連接埠

[root@localhost sunjimeng]# ss -l
Netid State  Recv-Q Send-Q Local Address:Port Peer Address:Port
nl    UNCONN 0      0      rtnl:NetworkManager/929 *
u_dgr UNCONN 0      0      * 246524 * 1492
raw   UNCONN 0      0      :::ipv6-icmp :::*
tcp   LISTEN 0      128    *:ssh   *:*
tcp   LISTEN 0      128    127.0.0.1:ipp  *:*
tcp   LISTEN 0      100    127.0.0.1:smtp *:*
tcp   LISTEN 0      128    :::ssh  :::*
tcp   LISTEN 0      100    ::1:smtp ::::*

4. 顯示占用 socket 的進程

[root@localhost sunjimeng]# ss -t -a -p
State  Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0      128    *:ssh   *:*      users:(("sshd",1324,3))
LISTEN 0      128    127.0.0.1:ipp  *:*   users:(("cupsd",3130,12))
LISTEN 0      100    127.0.0.1:smtp *:*   users:(("master",2575,13))
LISTEN 0      128    :::ssh  :::*     users:(("sshd",1324,4))
LISTEN 0      100    ::1:smtp :::*     users:(("master",2575,14))

5. 搭配 grep 過濾

[root@localhost sunjimeng]# ss -pl | grep 1487
u_str LISTEN 0 128 /run/systemd/journal/stdout 1487 * 0
      users:(("systemd-journal",617,3),("systemd",1,25))

6. 兩個命令的時間對比

[root@localhost sunjimeng]# time ss
real    0m0.081s
user    0m0.000s
sys     0m0.004s

[root@localhost sunjimeng]# time netstat
real    0m0.018s
user    0m0.004s
sys     0m0.000s

小規模連線下差異不明顯,但連線數一多,ss 的優勢就會被放大,實務上建議優先改用 ss。

Copyright © Linux教程網 All Rights Reserved