netstat命令在Linux上的用法

本文概述

  • 建立的连接
  • 监听连接
  • PID使用的端口号
  • 所有协议统计
  • 内核路由信息
  • 端口号使用的PID
  • 网络接口列表
  • 持续监听
了解什么是netstat命令以及一些实时示例。
netstat(网络统计信息)是一个命令行工具, 可显示网络连接(入站和出站), 路由表以及许多网络接口统计信息。
它在Linux, 类Unix和Windows操作系统上可用。 netstat功能强大, 可以作为解决网络相关问题和验证连接统计信息的便捷工具。
如果键入netstat -help, 将获得以下使用准则。
[[email  protected] ~]# netstat -help usage: netstat [-vWeenNcCF] [< Af> ] -rnetstat {-V|--version|-h|--help} netstat [-vWnNcaeol] [< Socket> ...] netstat { [-vWeenNac] -I[< Iface> ] | [-veenNac] -i | [-cnNe] -M | -s [-6tuw] } [delay]-r, --routedisplay routing table -I, --interfaces=< Iface> display interface table for < Iface> -i, --interfacesdisplay interface table -g, --groupsdisplay multicast group memberships -s, --statisticsdisplay networking statistics (like SNMP) -M, --masqueradedisplay masqueraded connections-v, --verbosebe verbose -W, --widedon't truncate IP addresses -n, --numericdon't resolve names --numeric-hostsdon't resolve host names --numeric-portsdon't resolve port names --numeric-usersdon't resolve user names -N, --symbolicresolve hardware names -e, --extenddisplay other/more information -p, --programsdisplay PID/Program name for sockets -o, --timersdisplay timers -c, --continuouscontinuous listing-l, --listeningdisplay listening server sockets -a, --alldisplay all sockets (default: connected) -F, --fibdisplay Forwarding Information Base (default) -C, --cachedisplay routing cache instead of FIB -Z, --contextdisplay 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) [[email  protected] ~]#

让我向你展示一些命令示例。以下内容已在RHEL / CentOS上进行了测试, 但我看不出有任何理由不能在其他发行版(如Ubuntu)上使用。
建立的连接如果要查找服务器中所有已建立的连接。
[[email  protected] ~]# netstat -natu | grep 'ESTABLISHED' tcp021 68.183.37.102:22222.186.31.135:21714ESTABLISHED tcp036 68.183.37.102:2252.148.155.182:49859ESTABLISHED tcp00 68.183.37.102:2261.177.142.158:55481ESTABLISHED [[email  protected] ~]#

如果你建立了许多连接并且对查找其中一个IP感兴趣, 则可以使用另一个grep。
[[email  protected] ~]# netstat -natu | grep 'ESTABLISHED' | grep 61.177.142.158 tcp01280 68.183.37.102:2261.177.142.158:33932ESTABLISHED [[email  protected] ~]#

监听连接【netstat命令在Linux上的用法】假设你已经启动了某些服务, 并且应该在特定的IP:Port上进行侦听, 这将很容易进行验证。
[[email  protected] ~]# netstat -an | grep 'LISTEN' tcp00 127.0.0.1:250.0.0.0:*LISTEN tcp00 0.0.0.0:1110.0.0.0:*LISTEN tcp00 0.0.0.0:220.0.0.0:*LISTEN tcp600 :::111:::*LISTEN tcp600 :::80:::*LISTEN tcp600 :::22:::*LISTEN [[email  protected] ~]#

或者, 你可以使用-l参数显示所有监听套接字。
[[email  protected] ~]# netstat -l Active Internet connections (only servers) Proto Recv-Q Send-Q Local AddressForeign AddressState tcp00 localhost:smtp0.0.0.0:*LISTEN tcp00 0.0.0.0:sunrpc0.0.0.0:*LISTEN tcp00 0.0.0.0:ssh0.0.0.0:*LISTEN tcp600 [::]:sunrpc[::]:*LISTEN tcp600 [::]:webcache[::]:*LISTEN tcp600 [::]:ssh[::]:*LISTEN udp00 0.0.0.0:8050.0.0.0:* udp00 0.0.0.0:sunrpc0.0.0.0:* udp00 localhost:3230.0.0.0:* udp600 [::]:805[::]:* udp600 [::]:sunrpc[::]:* udp600 ip6-localhost:323[::]:* Active UNIX domain sockets (only servers) Proto RefCnt FlagsTypeStateI-NodePath unix2[ ACC ]STREAMLISTENING15108/run/dbus/system_bus_socket unix2[ ACC ]STREAMLISTENING8202/run/systemd/journal/stdout unix2[ ACC ]SEQPACKETLISTENING12813/run/udev/control unix2[ ACC ]STREAMLISTENING17542public/pickup unix2[ ACC ]STREAMLISTENING15165/var/run/rpcbind.sock unix2[ ACC ]STREAMLISTENING17546public/cleanup unix2[ ACC ]STREAMLISTENING15605/var/lib/gssproxy/default.sock unix2[ ACC ]STREAMLISTENING12706/run/systemd/private unix2[ ACC ]STREAMLISTENING17549public/qmgr unix2[ ACC ]STREAMLISTENING17571public/flush unix2[ ACC ]STREAMLISTENING17553private/tlsmgr unix2[ ACC ]STREAMLISTENING17586public/showq unix2[ ACC ]STREAMLISTENING17556private/rewrite unix2[ ACC ]STREAMLISTENING17559private/bounce unix2[ ACC ]STREAMLISTENING17562private/defer unix2[ ACC ]STREAMLISTENING17565private/trace unix2[ ACC ]STREAMLISTENING17568private/verify unix2[ ACC ]STREAMLISTENING17574private/proxymap unix2[ ACC ]STREAMLISTENING17577private/proxywrite unix2[ ACC ]STREAMLISTENING17580private/smtp unix2[ ACC ]STREAMLISTENING17583private/relay unix2[ ACC ]STREAMLISTENING17589private/error unix2[ ACC ]STREAMLISTENING17592private/retry unix2[ ACC ]STREAMLISTENING17595private/discard unix2[ ACC ]STREAMLISTENING17598private/local unix2[ ACC ]STREAMLISTENING17601private/virtual unix2[ ACC ]STREAMLISTENING17604private/lmtp unix2[ ACC ]STREAMLISTENING17607private/anvil unix2[ ACC ]STREAMLISTENING17610private/scache unix2[ ACC ]STREAMLISTENING15606/run/gssproxy.sock [[email  protected] ~]#

利用grep筛选结果。
PID使用的端口号你知道你的应用程序已启动, 并且知道PID(进程标识符), 但不确定使用的端口号是什么。以下示例适用于PID 3937
[[email  protected] ~]# netstat -anlp |grep 3937 tcp600 :::80:::*LISTEN3937/httpd unix3[ ]STREAMCONNECTED24423873937/httpd [[email  protected] ~]#

如你所见, 端口80正在用于PID 3937。
所有协议统计是否由于丢弃数据包而频繁断开连接? -s参数将显示总体统计信息, 你可以在其中关注丢弃的消息包。
[[email  protected] ~]# netstat -s Ip: 731422 total packets received 0 forwarded 0 incoming packets discarded 731399 incoming packets delivered 787732 requests sent out 16 dropped because of missing route Icmp: 5277 ICMP messages received 120 input ICMP message failed. InCsumErrors: 6 ICMP input histogram: destination unreachable: 193 timeout in transit: 16 echo requests: 5060 echo replies: 2 9355 ICMP messages sent 0 ICMP messages failed ICMP output histogram: destination unreachable: 4295 echo replies: 5060 IcmpMsg: InType0: 2 InType3: 193 InType8: 5060 InType11: 16 OutType0: 5060 OutType3: 4295 Tcp: 42 active connections openings 35226 passive connection openings 1693 failed connection attempts 645 connection resets received 2 connections established 646705 segments received 648037 segments send out 99463 segments retransmited 27377 bad segments received. 150893 resets sent InCsumErrors: 27377 Udp: 74547 packets received 4814 packets to unknown port received. 56 packet receive errors 74584 packets sent 0 receive buffer errors 0 send buffer errors InCsumErrors: 56 UdpLite: TcpExt: 177 invalid SYN cookies received 1693 resets received for embryonic SYN_RECV sockets 316 TCP sockets finished time wait in fast timer 3 packets rejects in established connections because of timestamp 70248 delayed acks sent 6 delayed acks further delayed because of locked socket Quick ack mode was activated 3082 times 17 SYNs to LISTEN sockets dropped 28179 packets directly queued to recvmsg prequeue. 9802 bytes directly received in process context from prequeue 72106 packet headers predicted 94182 acknowledgments not containing data payload received 40094 predicted acknowledgments 332 times recovered from packet loss by selective acknowledgements 8 congestion windows recovered without slow start by DSACK 1173 congestion windows recovered without slow start after partial ack 1029 timeouts after SACK recovery 8 timeouts in loss state 329 fast retransmits 3 forward retransmits 32 retransmits in slow start 44785 other TCP timeouts TCPLossProbes: 9763 TCPLossProbeRecovery: 1732 54 SACK retransmits failed 3144 DSACKs sent for old packets 4 DSACKs sent for out of order packets 695 DSACKs received 1 DSACKs for out of order packets received 44 connections reset due to unexpected data 76 connections reset due to early user close 6079 connections aborted due to timeout TCPDSACKIgnoredNoUndo: 448 TCPSpuriousRTOs: 5 TCPSackShiftFallback: 465 IPReversePathFilter: 11 TCPRcvCoalesce: 32369 TCPOFOQueue: 4313 TCPOFOMerge: 4 TCPChallengeACK: 2 TCPSynRetrans: 43670 TCPOrigDataSent: 208010 TCPACKSkippedSeq: 12 IpExt: InNoRoutes: 12 InOctets: 133789295 OutOctets: 151093769 InNoECTPkts: 731338 InECT1Pkts: 3 InECT0Pkts: 1568 InCEPkts: 108 [[email  protected] ~]#

内核路由信息遇到路由问题?还是由于连接正在通过另一条路由而导致连接无法正常工作?
快速检查路由表。
[[email  protected] ~]# netstat -r Kernel IP routing table DestinationGatewayGenmaskFlagsMSS Windowirtt Iface defaultgateway0.0.0.0UG0 00 eth0 10.16.0.00.0.0.0255.255.0.0U0 00 eth0 68.183.32.00.0.0.0255.255.240.0U0 00 eth0 link-local0.0.0.0255.255.0.0U0 00 eth0 [[email  protected] ~]#

端口号使用的PID解决端口冲突问题非常方便。假设你正在尝试启动Apache或Nginx服务器, 该服务器侦听端口80, 但不能启动, 因为某些其他进程已经在使用端口80。
[[email  protected] ~]# netstat -anlp |grep 80 | grep LISTEN tcp600 :::80:::*LISTEN3937/httpd [[email  protected] ~]#

并且, 你可以看到PID 3937正在使用该端口。
如果你使用的是AIX, 则
netstat -Aan | grep $portnumber

这将以十六进制显示协议控制块的地址
一旦有了十六进制, 则可以在下面执行以获取进程保持端口号。
rmsock $address_of_pcb tcpcb

网络接口列表有多个以太网接口?还是不确定并想找出答案?
[[email  protected] ~]# netstat -i Kernel Interface table IfaceMTURX-OK RX-ERR RX-DRP RX-OVRTX-OK TX-ERR TX-DRP TX-OVR Flg eth0150079302600 0849443000 BMRU lo65536600 06000 LRU [[email  protected] ~]#

持续监听解决服务崩溃相关问题时的绝佳选择。假设某个应用每隔几分钟随机崩溃。但是, 不确定确切的时间。你可以使用-c参数, 该参数将连续显示结果。
[[email  protected] ~]# netstat -anlpc |grep 8080 tcp600 :::8080:::*LISTEN11766/httpd tcp600 :::8080:::*LISTEN11766/httpd tcp600 :::8080:::*LISTEN11766/httpd tcp600 :::8080:::*LISTEN11766/httpd

当它停止更新时, 你就知道它崩溃了。
总结
netstat是sysadmin广泛使用的命令之一, 我希望以上示例可以使你了解如何使用它。如果你想了解有关Linux管理的更多信息, 请查看此Udemy课程。

    推荐阅读