取代 netstat 的 ss

之前只知道有个 -s 能看到目前系统连接数的整体情况,实际上 ss 远比这个强大,远比 netstat 强大,最大的特点就是快。
$ ss -s

本地打开的端口:
$ ss -l
$ ss -ln
$ ss -lp

TCP,UDP,RAW,UNIX sockets:
$ ss -t -a
$ ss -u -a
$ ss -w -a
$ ss -x -a

如果某些协议修改了端口,要么要修改 services 对应的 port/service-name 要么就要直接使用数值的方式显示,比如我把 sshd 的端口修改成 11111:
$ ss -o state established '( dport = :11111 or sport = :11111 )' -p
Recv-Q Send-Q                                                                           Local Address:Port                                                                               Peer Address:Port  
0      256                                                                               11.11.111.21:11111                                                                           222.222.222.162:47868    timer:(on,207ms,0)
0      0                                                                                 11.11.111.21:11111                                                                           222.222.222.162:64872    timer:(keepalive,73min,0)
0      0                                                                                  192.18.10.15:11111                                                                               192.18.10.14:32984    timer:(keepalive,50min,0)

如果不修改 services 而直接使用的话,会找不到:
$ ss -o state established '( dport = :ssh or sport = :ssh )' -p
Recv-Q Send-Q                                                                           Local Address:Port                                                                               Peer Address:Port  

state 后面可以接下面这些参数:
established
syn-sent
syn-recv
fin-wait-1
fin-wait-2
time-wait
closed
close-wait
last-ack
listen
closing
all : All of the above states
connected : All the states except for listen and closed
synchronized : All the connected states except for syn-sent
bucket : Show states, which are maintained as minisockets, i.e. time-wait and syn-recv.
big : Opposite to bucket state.

一些常用方法:
$ ss -o state fin-wait-1 '( sport = :http or sport = :https )' dst 193.233.7/24
$ ss -x src /tmp/.X11-unix/*

$ ss dst 192.168.1.5
$ ss dst 192.168.1.5:443
$ ss src 75.126.153.214:80
 
$ ss  sport = :http
$ ss  dport \> :1024
$ ss sport \< :32000
$ ss  sport eq :22
$ ss  dport != :22
$ ss  state connected sport = :http
$ ss \( sport = :http or sport = :https \)
$ ss -o state fin-wait-1 \( sport = :http or sport = :https \) dst 192.168.1/24

遇到 "(" 等符号需要转义,要么使用 "\" 要么使用 "'"。

ref:
http://www.cyberciti.biz/tips/linux-investigate-sockets-network-connections.html
http://www.cyberciti.biz/files/ss.html