netstat 命令可以帮助检查本机的网络状况,man netstat 可以看到对其的基本描述:
netstat - Print network connections, routing tables, interface statistics, masquerade connections, and multicast memberships
先来一个简单的例子,要显示tcp协议,使用-t参数,包括了tcp和tcp6
- netstat-t
- ActiveInternetconnections(w/oservers)
- ProtoRecv-QSend-QLocalAddressForeignAddressState
- tcp00localhost:59226localhost:8527ESTABLISHED
- tcp00bogon:44385117.79.93.222:httpTIME_WAIT
- tcp00localhost:8527localhost:59305CLOSE_WAIT
- tcp00localhost:8527localhost:59235ESTABLISHED
- tcp01bogon:36113tf-in-f19.1e100.n:httpsSYN_SENT
- tcp00bogon:49941117.79.93.196:httpTIME_WAIT
- tcp00bogon:53574117.79.93.208:httpESTABLISHED
- tcp00localhost:59259localhost:8527ESTABLISHED
数量太多,只显示了一部分。
添加一个-l参数,会只显示监听本地端口的TCP程序,现在一下子程序少了很多。
- netstat-tl
- ActiveInternetconnections(onlyservers)
- ProtoRecv-QSend-QLocalAddressForeignAddressState
- tcp00localhost:8527*:*LISTEN
- tcp00*:http*:*LISTEN
- tcp00localhost:domain*:*LISTEN
- tcp00localhost:ipp*:*LISTEN
- tcp00*:https*:*LISTEN
- tcp600ip6-localhost:8527[::]:*LISTEN
- tcp600ip6-localhost:ipp[::]:*LISTEN
注意上面的Local Address一列,显示的不是ip地址,而是localhost, 如果想要显示IP地址,添加一个参数-n
- netstat-tln
- ActiveInternetconnections(onlyservers)
- ProtoRecv-QSend-QLocalAddressForeignAddressState
- tcp00127.0.0.1:85270.0.0.0:*LISTEN
- tcp000.0.0.0:800.0.0.0:*LISTEN
- tcp00127.0.0.1:530.0.0.0:*LISTEN
- tcp00127.0.0.1:6310.0.0.0:*LISTEN
- tcp000.0.0.0:4430.0.0.0:*LISTEN
- tcp600::1:8527:::*LISTEN
- tcp600::1:631:::*LISTEN
如果还想显示进程名称和ID,再添加一个参数-p
- netstat-tlnp
- ActiveInternetconnections(onlyservers)
- ProtoRecv-QSend-QLocalAddressForeignAddressStatePID/Programname
- tcp00127.0.0.1:85270.0.0.0:*LISTEN6506/ssh
- tcp000.0.0.0:800.0.0.0:*LISTEN889/nginx
- tcp00127.0.0.1:530.0.0.0:*LISTEN1268/dnsmasq
- tcp00127.0.0.1:6310.0.0.0:*LISTEN590/cupsd
- tcp000.0.0.0:4430.0.0.0:*LISTEN889/nginx
- tcp600::1:8527:::*LISTEN6506/ssh
- tcp600::1:631:::*LISTEN590/cupsd
配合grep,就可以查找监听本地某端口的进程
- netstat-tlnp|grep127.0.0.1:8527
- tcp00127.0.0.1:85270.0.0.0:*LISTEN6506/ssh
配合awk,就可以快速找到进程名称
- netstat-tlnp|grep127.0.0.1:8527|awk'{print$7}'
- 7458/ssh
再做一次awk查找,去掉斜线后面的,只保留进程id
- netstat-tlnp|grep127.0.0.1:8527|awk'{print$7}'|awk-F'/''{print$1}'
- 7458