這兩天實驗室網絡不給力,后來發現是有人占用了實驗室太多的帶寬,而登陸到實驗室老的h3c s5500交換機上看端口流量情況很不方便,於是萌生寫個小工具來統計端口流量情況,已求找到誰占用了大量帶寬。
於是查了下,發現python 有個telnetlib的庫,登陸交換機以及進行簡單的操作相當簡單,於是就寫了這么個小工具:
*************************************工作原理********************************************
1、本程序采用telnet的方式登陸到交換機並通過不停的發送display interface [接口] 的方式請求交換機接口
信息並從中提取total input 和 total output的方式計算當前端口速率。
2、本程序僅統計狀態為UP的端口的信息。使用display brief interface獲取到狀態為UP的接口。
3、本程序僅統計gigabytes端口。
*************************************其他**********************************************
1、第一次統計信息,由於沒有時間,信息不准確
2、速度的單位都是MB
3、統計結果只能作為參考,並不能代表速率。
4、由於交換機本身更新接口信息速度並不快,而且telnet發送命令回傳耗時也較大,本程序設置最小刷新時間,
當前為5s,若由於請求交換機接口所耗時超過5s,則刷新時間為請求耗時時間。
#!/usr/bin/python
import re
import telnetlib
import time
import platform
import os
Host = '.....'
username = ''
password = ''
finish = '<....>'
MIN_INTERVAL = 5.0 # use float
PORT_COUNT = 52 # h3c s5500 has 52 gigabyte ports
# return system type as a string
def get_system_info():
sys_platform = platform.system()
if sys_platform == 'Linux' or sys_platform == 'Darwin':
return 'UNIX'
elif sys_platform == 'Windows':
return 'WINDOWS'
else:
return 'UNIX'
def clear_screen():
sys_type = get_system_info()
if sys_type == 'UNIX':
os.system("clear")
elif sys_type == 'WINDOWS':
os.system('cls')
else:
os.system('clear')
# login to the device and return the Telnet object
def login():
# telnet to the device
print 'connect...'
tn = telnetlib.Telnet(Host,timeout = 5)
tn.read_until('Username:',timeout=5)
tn.write(username + '\n')
tn.read_until('Password:')
tn.write(password + '\n')
tn.read_until(finish)
print 'telnet success'
return tn
#'''using Telnet object to get port status and return a tuple filled with 'UP' ports'''
def get_up_ports(tn):
example = '''
The brief information of interface(s) under bridge mode:
Interface Link Speed Duplex Link-type PVID
GE1/0/1 UP 100M(a) full(a) access 409
GE1/0/2 UP 100M(a) full(a) access 409
GE1/0/3 DOWN auto auto access 409'''
tn.write('display brief interface\n')
tn.write(' ')
tn.write(' ')
ports_brief = tn.read_until(finish)
up_ports = []
port_info = re.findall(r"GE1/0/(\d+)(\s+)(\w+)",ports_brief)
for i in port_info:
if i[-1] == 'UP':
up_ports.append(i[0])
print up_ports
return tuple(up_ports)
def extract_data(port_str):
''' get the data from the result of command 'display interface GigabitEthernet 1/0/i'
'''
# (VLAN_ID, total_input, total_output, max_input, max_output)
if re.search('GigabitEthernet', port_str) == None:
return None
VLAN_ID_list = re.findall(r"PVID: (\d+)",port_str)
input_total_list = re.findall(r"Input \(total\): (\d+) packets, (\d+) bytes", port_str)
output_total_list = re.findall(r"Output \(total\): (\d+) packets, (\d+) bytes", port_str)
peak_input_list = re.findall(r"Peak value of input: (\d+) bytes/sec,", port_str);
peak_output_list = re.findall(r"Peak value of output: (\d+) bytes/sec,", port_str);
state_list = re.findall(r"current state: (.+)",port_str)
VLAN_ID = VLAN_ID_list[0] # string
input_total = long((list(input_total_list[0]))[1]) # long
output_total = long((list(output_total_list[0]))[1]) # long
peak_input = long(peak_input_list[0]) # long
peak_output = long(peak_output_list[0]) # long
state = str(state_list[0]) # string
return (VLAN_ID, input_total, output_total, peak_input, peak_output, state)
def do_statistic():
last_input = [0] * PORT_COUNT
last_output = [0] * PORT_COUNT
last_update = time.time()
tn = login()
up_ports = get_up_ports(tn)
clear_screen()
print 'connected, waiting...'
while(True):
ports_str = []
# h3c s5500 g1/0/1 - g1/0/52
# input command to get output
for i in up_ports:
tn.write('display interface GigabitEthernet 1/0/' + str(i) +'\n')
tn.write(' ')
port_info = tn.read_until(finish)
ports_str.append(port_info)
# get interval
interval = (time.time() - last_update)
if interval < MIN_INTERVAL:
time.sleep(MIN_INTERVAL - interval)
interval = MIN_INTERVAL
# get data and print
clear_screen()
print "the input/output is from the port view of the switch."
print "From the user's view: input <-> download; output <-> upload."
print "the VLAN 1000 is connected to the firewall. So, it's opposite\n\n"
print 'PORT_NO\tVLAN_ID\tINPUT\tOUTPUT\tMAX_IN\tMAX_OUT\tSTATE (MB)'
port_index = 0
for _port_str in ports_str:
# (VLAN_ID, total_input, total_output, max_input, max_output)
data = extract_data(_port_str)
if data == None:
continue
port_no = up_ports[port_index]
vlan_id = data[0]
speed_input = (data[1] - last_input[port_index]) / (interval * 1024 * 1024)
speed_output = (data[2] - last_output[port_index]) / (interval * 1024 * 1024)
max_input = data[3] / (1024 * 1024 )
max_output = data[4] / (1024 * 1024 )
state = data[5]
last_input[port_index] = data[1]
last_output[port_index] = data[2]
port_index += 1
# show
print port_no, '\t', vlan_id, '\t',float('%.2f' %speed_input), '\t', float('%.2f' %speed_output), '\t',
print float('%.2f' %max_input), '\t' ,float('%.2f' %max_output), '\t', state
last_update = time.time()
if __name__ == "__main__":
username = raw_input("please input username:")
password = raw_input("please input password:")
print username
print password
do_statistic()
tn.close()
代碼未做異常處理,僅實現了簡單的流量統計功能。
