Python获取服务器网速


实时获取服务器网速的脚本

CentOS6版本


#!/usr/bin/python

import os, re, time

def get_net():
    return re.search('eth0: (\d+)(\d+\s+){8}(\d+)', os.popen('cat /proc/net/dev').read())

first = get_net()

time.sleep(1)

second = get_net()

recive_speed = (int(second.group(1)) - int(first.group(1))) / 1024
send_speed = (int(second.group(3)) - int(first.group(3))) / 1024

recive_company = 'K/s'
send_company = 'K/s'

if send_speed > 1024:
    send_speed = send_speed / 1024
    send_company = 'M/s'

print('Recive : ' + str(recive_speed) + recive_company)
print('Send : ' + str(send_speed) + send_company)

CentOS7版本


#!/usr/bin/python

import os, re, time

def get_net():
    return re.findall('\d+', os.popen('cat /proc/net/dev | grep ens33').read())

first = get_net()
time.sleep(1)
second = get_net()

recive_speed = (int(second[1]) - int(first[1])) / 1024
send_speed = (int(second[9]) - int(first[9])) / 1024

recive_company = 'K/s'
send_company = 'K/s'

if send_speed > 1024:
    send_speed = send_speed / 1024
    send_company = 'M/s'

if recive_speed > 1024:
    recive_speed = recive_speed / 1024
    recive_company = 'M/s'

print('Recive : ' + str(recive_speed) + recive_company)
print('Send : ' + str(send_speed) + send_company)

使用办法:
将此脚本保存到 /usr/local/bin/ 目录下,命名为 speed
添加可执行权限:chmod +x speed
watch -n 1 speed