这两天实验室网络不给力,后来发现是有人占用了实验室太多的带宽,而登陆到实验室老的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,则刷新时间为请求耗时时间。

python3(未调试通过)

#!/usr/bin/pythonimport re
import telnetlib
import time
import platform
import osHost = '192.168.2.65'
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 deviceprint("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  PVIDGE1/0/1              UP        100M(a)      full(a)  access     409GE1/0/2              UP        100M(a)      full(a)  access     409GE1/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 NoneVLAN_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]                                       # stringinput_total     = long((list(input_total_list[0]))[1])          # longoutput_total    = long((list(output_total_list[0]))[1])         # longpeak_input      = long(peak_input_list[0])                      # longpeak_output     = long(peak_output_list[0])                     # longstate           = str(state_list[0])                            # stringreturn (VLAN_ID, input_total, output_total, peak_input, peak_output, state)def do_statistic():last_input = [0] * PORT_COUNTlast_output = [0] * PORT_COUNTlast_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 outputfor 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 intervalinterval = (time.time() - last_update)if interval < MIN_INTERVAL:time.sleep(MIN_INTERVAL - interval)interval = MIN_INTERVAL# get data and printclear_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 = 0for _port_str in ports_str:# (VLAN_ID, total_input, total_output, max_input, max_output)data = extract_data(_port_str)if data == None:continueport_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# showprint(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 = input("please input username:")password = input("please input password:")print(username)print(password)do_statistic()tn.close()

python2

原文:https://www.cnblogs.com/ljxuan/p/3966732.html

【网络】H3C 交换机telnet查看端口流量Python小工具相关推荐

  1. 查看san交换机端口流量_H3C 交换机telnet查看端口流量小工具

    这两天实验室网络不给力,后来发现是有人占用了实验室太多的带宽,而登陆到实验室老的h3c s5500交换机上看端口流量情况很不方便,于是萌生写个小工具来统计端口流量情况,已求找到谁占用了大量带宽. 于是 ...

  2. python日历小程序_一个查看网络设备信息Python小程序

    原标题:一个查看网络设备信息Python小程序 网络编程中,最常见的一个问题就是,获取设备信息. 首先我们,要学习如何获取本机的网络信息.我们将用到标准库中的socket库.假如说,我们要查看本机的 ...

  3. tcping扫描所有端口_ping TCP端口的实用小工具tcping

    原标题:ping TCP端口的实用小工具tcping ping 大家都很熟悉的ping 命令,属于网络层的ICMP协议,只能检查 IP 的连通性或网络连接速度, 无法检测IP的端口状态. telnet ...

  4. python小工具myqr生成动态二维码

    python小工具myqr生成动态二维码 (一)安装 (二)使用 (一)安装 命令: pip install myqr 安装完成后,就可以在命令行中输入 myqr 查看下使用帮助: myqr --he ...

  5. Python小工具——唐诗三百首朗读

    Python小工具--唐诗三百首朗读 工具简介 系统语音朗读唐诗三百首,可自己选择要朗读的唐诗,可搜索查找唐诗进行朗读,可用于幼儿园或小学生熟悉唐诗,积累文学素养. 工具界面 1.打开工具 可查看当前 ...

  6. 自己整理实现的python小工具

    文章目录 记录一些自己整理实现的python小工具 python获取文件路径 pytho使用opencv进行图像拼接 记录一些自己整理实现的python小工具 python获取文件路径 因为有的程序需 ...

  7. python小工具—图片转为字符txt

    python小工具-图片转为字符txt 图片转为字符txt python小工具-图片转为字符txt 效果展示 转换图片信息 图片信息转字符 完整代码 效果展示 转换图片信息 将图片的rgb色彩信息转为 ...

  8. 【Python小工具】若干图片合并生成动态图(.gif)

    相信很多学生党.上班族在日常的学习.科研.办公中总会有一些比较特殊的需求,本人作为一个理工科(非计算机相关专业)学生和大家一样.有时好不容易找到了比较心仪的工具,却发现还要收费,质量和使用的便捷性也不 ...

  9. 自制python小工具(3)——Gadgets1.1

    自制python小工具(3)--Gadgets 1.1 文章目录 自制python小工具(3)--Gadgets 1.1 1. 前言 2. 功能实现 2.1 主程序界面 2.1.1 标签与按钮 2.1 ...

最新文章

  1. Linux性能研究(总)
  2. Ubuntu18.04+RTX 2080Ti+CUDA 10.0 +cuDNN+PyTorch搭建深度学习环境
  3. python从random生成列表_Python 学习DAY 17 列表生成式,生成器,迭代器,time模块,random模块...
  4. TensorFlow2-卷积神经网络
  5. vue 数组数据改变 视图不更新解决方案
  6. 什么是A记录,子域名,CNAME别名,MX记录,TXT记录,SRV 记录,泛域名(泛解析),域名转向,域名绑定...
  7. linux jmeter 内存,怎么在Linux下改变JMeter内存
  8. ajax、axios、fetch之间的详细区别以及优缺点
  9. Android混淆注意事项
  10. 企业财务报表分析【1】
  11. Vue核心技术-40,vue-router-编程式路由导航
  12. (补)蒟蒻信安笔记1.5:(Nmap的使用部分)原来是这么个神奇的原因导致无法进行
  13. K8S学习之容器探测 livenessProbe、readinessProbe、startupProbe、lifecycle
  14. ai旋转扭曲_AI变换及旋转图形工具详解
  15. 从SSCHA安装解析python setup.py
  16. python人工智能计算器_python游戏dnf_招募:基于python的召唤师全时段全技能(含均值AI)计算器全程测试......
  17. 助力阿米巴经营,实现数字化转型——普元阿米加系统架构与实践
  18. 2020 MICCAI Shape-aware Meta-learning for Generalizing Prostate MRI Segmentation to Unseen Domains
  19. Linux服务器Anaconda安装Pytorch(注意,前方有大坑)
  20. wdr6500 php,WDR6500成功刷上OpenWrt!!!附上教程。

热门文章

  1. 抖音用计算机打电话怎么按,抖音怎么用一部手机进行电脑直播
  2. pandas数据分组聚合——groupby()、aggregate()、apply()、transform()和filter()方法详解
  3. 游戏手机评测之摩托罗拉E398
  4. poi实现word文档转pdf格式
  5. 10649物联卡查询, 10649物联卡官网
  6. 人脸识别与美颜算法实战-图像特效
  7. 微信小程序之设置所有页面背景颜色
  8. 从事热爱的工作和积极乐观
  9. latex表格中如何画虚线
  10. 龙泉寺贤超法师:用AI为古籍经书识别、断句、翻译