Linux에서 netstat 명령 사용
게시 됨: 2015-02-15netstat 명령과 실시간 예가 무엇인지 알아보십시오.
netstat
(네트워크 통계)는 네트워크 연결(수신 및 발신 모두), 라우팅 테이블 및 여러 네트워크 인터페이스 통계를 표시하는 명령줄 도구입니다.
Linux, Unix 계열 및 Windows 운영 체제에서 사용할 수 있습니다. netstat
는 강력하며 네트워크 관련 문제를 해결하고 연결 통계를 확인하는 편리한 도구가 될 수 있습니다.
netstat -help
를 입력하면 다음과 같은 사용 지침이 표시됩니다.
[root@lab ~]# netstat -help 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) [root@lab ~]#
명령의 몇 가지 예를 보여드리겠습니다. 다음은 RHEL/CentOS에서 테스트되었지만 Ubuntu와 같은 다른 배포판에서 작동하지 않을 이유가 없습니다.
연결 설정
서버에서 설정된 모든 연결을 찾는 경우.
[root@lab ~]# netstat -natu | grep 'ESTABLISHED' tcp 0 21 68.183.37.102:22 222.186.31.135:21714 ESTABLISHED tcp 0 36 68.183.37.102:22 52.148.155.182:49859 ESTABLISHED tcp 0 0 68.183.37.102:22 61.177.142.158:55481 ESTABLISHED [root@lab ~]#
많은 연결이 설정되어 있고 IP 중 하나를 찾는 데 관심이 있는 경우 다른 grep을 사용할 수 있습니다.
[root@lab ~]# netstat -natu | grep 'ESTABLISHED' | grep 61.177.142.158 tcp 0 1280 68.183.37.102:22 61.177.142.158:33932 ESTABLISHED [root@lab ~]#
청취 연결
어떤 서비스를 시작했고 특정 IP:Port에서 수신 대기해야 한다고 가정해 보겠습니다. 이는 확인하는 데 편리할 것입니다.
[root@lab ~]# netstat -an | grep 'LISTEN' tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN tcp6 0 0 :::111 :::* LISTEN tcp6 0 0 :::80 :::* LISTEN tcp6 0 0 :::22 :::* LISTEN [root@lab ~]#
또는 -l
인수를 사용하여 모든 수신 소켓을 표시할 수 있습니다.
[root@lab ~]# netstat -l Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 localhost:smtp 0.0.0.0:* LISTEN tcp 0 0 0.0.0.0:sunrpc 0.0.0.0:* LISTEN tcp 0 0 0.0.0.0:ssh 0.0.0.0:* LISTEN tcp6 0 0 [::]:sunrpc [::]:* LISTEN tcp6 0 0 [::]:webcache [::]:* LISTEN tcp6 0 0 [::]:ssh [::]:* LISTEN udp 0 0 0.0.0.0:805 0.0.0.0:* udp 0 0 0.0.0.0:sunrpc 0.0.0.0:* udp 0 0 localhost:323 0.0.0.0:* udp6 0 0 [::]:805 [::]:* udp6 0 0 [::]:sunrpc [::]:* udp6 0 0 ip6-localhost:323 [::]:* Active UNIX domain sockets (only servers) Proto RefCnt Flags Type State I-Node Path unix 2 [ ACC ] STREAM LISTENING 15108 /run/dbus/system_bus_socket unix 2 [ ACC ] STREAM LISTENING 8202 /run/systemd/journal/stdout unix 2 [ ACC ] SEQPACKET LISTENING 12813 /run/udev/control unix 2 [ ACC ] STREAM LISTENING 17542 public/pickup unix 2 [ ACC ] STREAM LISTENING 15165 /var/run/rpcbind.sock unix 2 [ ACC ] STREAM LISTENING 17546 public/cleanup unix 2 [ ACC ] STREAM LISTENING 15605 /var/lib/gssproxy/default.sock unix 2 [ ACC ] STREAM LISTENING 12706 /run/systemd/private unix 2 [ ACC ] STREAM LISTENING 17549 public/qmgr unix 2 [ ACC ] STREAM LISTENING 17571 public/flush unix 2 [ ACC ] STREAM LISTENING 17553 private/tlsmgr unix 2 [ ACC ] STREAM LISTENING 17586 public/showq unix 2 [ ACC ] STREAM LISTENING 17556 private/rewrite unix 2 [ ACC ] STREAM LISTENING 17559 private/bounce unix 2 [ ACC ] STREAM LISTENING 17562 private/defer unix 2 [ ACC ] STREAM LISTENING 17565 private/trace unix 2 [ ACC ] STREAM LISTENING 17568 private/verify unix 2 [ ACC ] STREAM LISTENING 17574 private/proxymap unix 2 [ ACC ] STREAM LISTENING 17577 private/proxywrite unix 2 [ ACC ] STREAM LISTENING 17580 private/smtp unix 2 [ ACC ] STREAM LISTENING 17583 private/relay unix 2 [ ACC ] STREAM LISTENING 17589 private/error unix 2 [ ACC ] STREAM LISTENING 17592 private/retry unix 2 [ ACC ] STREAM LISTENING 17595 private/discard unix 2 [ ACC ] STREAM LISTENING 17598 private/local unix 2 [ ACC ] STREAM LISTENING 17601 private/virtual unix 2 [ ACC ] STREAM LISTENING 17604 private/lmtp unix 2 [ ACC ] STREAM LISTENING 17607 private/anvil unix 2 [ ACC ] STREAM LISTENING 17610 private/scache unix 2 [ ACC ] STREAM LISTENING 15606 /run/gssproxy.sock [root@lab ~]#
결과를 필터링하려면 grep
을 활용하십시오.

PID가 사용하는 포트 번호
응용 프로그램이 시작되고 PID(Process Identifier)를 알고 있지만 사용 중인 포트 번호가 무엇인지 잘 모릅니다. 아래 예는 PID 3937에 대한 것입니다.
[root@lab ~]# netstat -anlp |grep 3937 tcp6 0 0 :::80 :::* LISTEN 3937/httpd unix 3 [ ] STREAM CONNECTED 2442387 3937/httpd [root@lab ~]#
보시다시피 포트 80은 PID 3937에 사용됩니다.
모든 프로토콜 통계
패킷 폐기로 인해 끊김이 자주 발생합니까? -s
인수는 패킷 폐기 메시지에 주의를 기울일 수 있는 전체 통계를 표시합니다.
[root@lab ~]# 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 [root@lab ~]#
커널 라우팅 정보
라우팅 문제가 있습니까? 또는 연결이 다른 경로를 통해 이동하기 때문에 연결이 예상대로 작동하지 않습니까?
라우팅 테이블을 빠르게 확인하십시오.
[root@lab ~]# netstat -r Kernel IP routing table Destination Gateway Genmask Flags MSS Window irtt Iface default gateway 0.0.0.0 UG 0 0 0 eth0 10.16.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth0 68.183.32.0 0.0.0.0 255.255.240.0 U 0 0 0 eth0 link-local 0.0.0.0 255.255.0.0 U 0 0 0 eth0 [root@lab ~]#
포트 번호에서 사용하는 PID
포트 충돌 문제를 해결하는 데 매우 편리합니다. 포트 80에서 수신 대기하지만 다른 프로세스가 이미 포트 80을 사용하고 있기 때문에 수신할 수 없는 Apache 또는 Nginx 서버를 시작하려고 한다고 가정해 보겠습니다.
[root@lab ~]# netstat -anlp |grep 80 | grep LISTEN tcp6 0 0 :::80 :::* LISTEN 3937/httpd [root@lab ~]#
그리고 PID 3937이 해당 포트를 사용하고 있는 것을 볼 수 있습니다.
AIX를 사용하는 경우
netstat -Aan | grep $portnumber
그러면 프로토콜 제어 블록의 주소가 16진수로 표시됩니다.
16진수가 있으면 아래에서 실행하여 포트 번호를 보유하고 있는 프로세스를 얻을 수 있습니다.
rmsock $address_of_pcb tcpcb
네트워크 인터페이스 목록
여러 이더넷 인터페이스가 있습니까? 또는 확실하지 않고 알고 싶으십니까?
[root@lab ~]# 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 793026 0 0 0 849443 0 0 0 BMRU lo 65536 6 0 0 0 6 0 0 0 LRU [root@lab ~]#
지속적인 듣기
서비스 충돌 관련 문제를 해결할 때 탁월한 옵션입니다. 응용 프로그램이 몇 분마다 무작위로 충돌한다고 가정해 보겠습니다. 그러나 정확히 언제인지는 확실하지 않습니다. 결과를 지속적으로 표시하는 -c
인수를 사용할 수 있습니다.
[root@lab ~]# netstat -anlpc |grep 8080 tcp6 0 0 :::8080 :::* LISTEN 11766/httpd tcp6 0 0 :::8080 :::* LISTEN 11766/httpd tcp6 0 0 :::8080 :::* LISTEN 11766/httpd tcp6 0 0 :::8080 :::* LISTEN 11766/httpd
업데이트가 중지되면 충돌했음을 알 수 있습니다.
결론
netstat
는 sysadmin에서 널리 사용되는 명령 중 하나이며 위의 예에서 이 명령으로 수행할 수 있는 작업에 대한 아이디어를 얻을 수 있기를 바랍니다. Linux 관리에 대해 자세히 알아보려면 이 Udemy 과정을 확인하십시오.