Linux 是一种功能强大、开放可扩展性强的操作系统。在实际应用中,网络是 Linux 运行的关键。我们要深入了解 Linux 的网络状况,就必须掌握 Linux 中的一个重要网络命令:netstat。
什么是 netstat 命令?
在 Linux 中,netstat 是一个非常重要的网络命令,可以用于查看网络连接状态、路由表、网络接口等信息。
netstat 会输出所有活动网络连接的信息,包括协议、本地地址、远程地址、状态、所属 PID 等,从而方便用户分析网络状态。
如何查看网络连接状态?
常用的 netstat 命令及参数如下:
netstat -a 显示所有连接
netstat -n 显示所有地址和端口号,不进行服务名称解析
netstat -o 显示所有进程 ID
netstat -r 显示路由表
netstat -s 显示网络统计信息
以下为示例:
# netstat -a
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 *:telnet *:* LISTEN
tcp 0 0 *:ssh *:* LISTEN
tcp 0 0 localhost:smtp *:* LISTEN
tcp 0 0 localhost:953 *:* LISTEN
tcp 0 0 localhost:mysql *:* LISTEN
tcp 0 44 example.com:ssh 192.168.1.12:20631 ESTABLISHED
tcp 0 0 example.com:ssh example.com:60142 ESTABLISHED
udp 0 0 *:domain *:*
udp 0 0 *:bootpc *:*
udp 0 0 localhost:ntp *:*
udp 0 0 localhost:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:ntp *:*
udp 0 0 *:isakmp *:*
udp 0 0 *:22827 *:*
raw 0 0 *:icmp *:* 7
说明:该示例是在服务器(example.com)上运行的,并且已经建立了一些 TCP 和 UDP 连接。
接下来,我们针对 netstat 命令进行一些技巧性讲解。
1.使用 netstat 命令进行端口扫描
使用以下命令可以进行端口扫描:
netstat -tn | grep -E '^tcp.*[1-9]{1,}$' | awk '{print $4}' | cut -d":" -f2 | sort | uniq
说明:这个命令输出了所有在本地被使用的 TCP 端口。
2.使用 netstat 命令进行进程端口占用查询
使用以下命令可以查询占用端口的进程:
netstat -nlp | grep :80
说明:这个命令查询所有占用端口为 80 的进程。
3.使用 netstat 命令查看网络连接历史
使用以下命令可以查看网络连接历史:
netstat -tunap | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n
说明:这个命令可以输出 TCP 和 UDP 连接中每个 IP 地址的使用次数。
4.使用 netstat 命令查看网络流量情况
使用以下命令可以查看网络流量情况:
netstat -s | awk '/^.*in.*packets/ {print $1" "$2" "$3} /^.*out.*packets/ {print $1" "$2" "$3}'
说明:这个命令可以输出在本地主机上收到和发送的数据包数。
总结
通过本文的讲解,我们已经了解了 netstat 命令的基本概念、常用参数以及使用技巧。在 Linux 网络调优中,正确使用 netstat 命令是非常重要的。通过使用 netstat 命令,我们可以方便地查看 Linux 的网络连接状态,及时了解网络状况,解决网络问题,保障网络的正常运行。