一个显示服务器当前网速的脚本

写一个脚本自己用。

Published @ Sep 21, 2014

有时候网站访问比较慢了,就想看看服务器当前的上行下行网速是多少。网上搜了一下发现貌似没有直接可用的工具,只能自己写个脚本了。

这个脚本的思路就是在ifconfig的结果的基础上添加显示对应的interface的网速,就把它叫做ifspeed吧,这个名字起码看起来比较高大上。

文件ifspeed内容如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
import time

if len(sys.argv) == 2:
    eths = [sys.argv[1]]
else:
    raw = os.popen("ifconfig").read().strip().split("\n\n")
    eths = [s.split(None, 1)[0] for s in raw]

old = {}

def print_info(eth):
    raw = os.popen("ifconfig " + eth).read().strip()
    ts = time.time()
    rx = int(re.search(r"RX bytes:(\d+)", raw).group(1))
    tx = int(re.search(r"TX bytes:(\d+)", raw).group(1))
    oldvalue = old.get(eth)
    if oldvalue:
        oldts, oldrx, oldtx = oldvalue
        spdrx = (rx - oldrx) / (ts - oldts) / 1024
        spdtx = (tx - oldtx) / (ts - oldts) / 1024
        spdinfo = "\n          RX speed:%.1f kBps  TX speed:%.1f kBps" \
            % (spdrx, spdtx)
        out = raw + spdinfo
    else:
        out = raw

    sys.stdout.write(out)
    sys.stdout.write("\n\n")
    sys.stdout.flush()

    old[eth] = (ts, rx, tx)


while True:
    os.system('cls' if os.name == 'nt' else 'clear')
    for eth in eths:
        print_info(eth)
    time.sleep(1)

看看效果吧:

~ » ifspeed
eth0      Link encap:Ethernet  HWaddr be:4e:ae:9e:be:4e
          inet addr:192.168.1.20  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::bc4e:aeff:fe9e:be4e/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:7822185 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3044230 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:2321603045 (2.3 GB)  TX bytes:2542711955 (2.5 GB)
          RX speed:0.2 kBps  TX speed:3.4 kBps

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:7886469 errors:0 dropped:0 overruns:0 frame:0
          TX packets:7886469 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:3355470528 (3.3 GB)  TX bytes:3355470528 (3.3 GB)
          RX speed:0.0 kBps  TX speed:0.0 kBps

每个Interface下面最后一行就是这个脚本添加的,输出数据会每秒自动刷新,效果还不错吧。

END