ubuntu如何回收网络带宽资源
小樊
39
2025-12-17 22:27:05
Ubuntu回收网络带宽资源的实用步骤
一、先定位占用带宽的进程与连接
- 安装并使用工具查看实时占用:
- iftop(按主机/端口看流量):sudo apt install iftop && sudo iftop -i eth0
- nethogs(按进程看带宽):sudo apt install nethogs && sudo nethogs eth0
- nload(入/出站趋势图):sudo apt install nload && nload eth0
- 清理无效连接与进程:
- 查看连接状态:ss -tulnp | grep TIME_WAIT(或 netstat -tulnp)
- 终止异常进程:sudo kill -9 (PID 来自 nethogs/iftop)
- 目的:快速识别异常下载、备份、P2P 或未关闭会话,为后续限速/停用提供依据。
二、限制占用带宽的应用或网卡
- 按进程限速(用户态,无需 root 即可限制该进程):
- 安装:sudo apt install trickle
- 启动并限速:trickle -d 300 -u 100 firefox(下载 300 KB/s、上传 100 KB/s)
- 全局守护:sudo trickled -d 1000(对所有通过 trickle 启动的程序生效,按策略共享带宽)
- 按网卡限速(系统级,适合整机上/下行保障):
- 安装:sudo apt install wondershaper
- 设定上限:sudo wondershaper eth0 1024 512(下载 1 Mbps、上传 512 Kbps)
- 清除规则:sudo wondershaper clear eth0
- 说明:wondershaper 底层使用 tc(Traffic Control)实现,能在限制带宽的同时尽量保持交互会话低延迟。
三、用 tc 做更精细的流量整形(可选)
- 令牌桶整形示例(限制接口总带宽,单位更灵活):
- 安装 iproute2:sudo apt install iproute2
- 应用规则:sudo tc qdisc add dev eth0 root tbf rate 1mbit burst 32kbit latency 400ms
- 清理规则:sudo tc qdisc del dev eth0 root
- 提示:tc 语法较复杂,适合需要队列、优先级、分层带宽等高级控制的场景。
四、清理系统级网络资源占用
- 释放无用地址与路由:
- 释放 IP:sudo ip addr del 192.168.1.100/24 dev eth0
- 刷新路由:sudo ip route flush table all
- 清理缓存与邻居表:
- DNS 缓存:sudo systemd-resolve --flush-caches
- ARP 缓存:sudo ip neigh flush all
- 适用场景:释放不再使用的 IP/路由/ARP/DNS 缓存,减少无效网络占用与潜在冲突。
五、优化与维护建议
- 关闭不必要的后台服务(如未使用的 FTP/Telnet):
- sudo systemctl stop ftp && sudo systemctl disable ftp
- 调整内核网络参数,缩短连接回收时间(谨慎评估线上业务):
- echo “net.ipv4.tcp_fin_timeout = 30” | sudo tee -a /etc/sysctl.conf
- sudo sysctl -p
- 建议:变更前备份配置,先在测试环境验证,避免影响关键业务。