用python+iperf3写一个“每跑一次我就多摸鱼一分钟”的网络吞吐量测试脚本

  • 对于新拿到的合板一般要先进行一波基础功能的测试,即对于一些功能接口(PoE,sd卡,喇叭,咪头等等)先进行初步的使用和测试。其中也包括对网络的测试,前段时间记录了纯手动xshell+cmd+iperf3的测试网络吞吐量的大小。为了提高效率,xshell可以添加一些快捷按钮。但是正好刚写了相关的其他脚本,随手一改我就能拥有摸鱼一分钟的快乐(也可以加个循环连续摸鱼十分钟)。
  • 影响主板网络通信的因素有很多。电脑作为服务器连了网线还是wifi,网线的长度,主板是否连接了灯板,电源是PoE还是DC,sd卡或者其他接口同时也在工作都会有或多或少的影响。结合我自己的情况,选择了100m网线+设定了50M的带宽,两种上电方式都要确保丢包率接近0才算ok。
  • 测试大体步骤是要用tftp将iperf3传送给设备,将cmd打开运行iperf3(作为server,每隔2秒跳出一次通信情况),语句如下。
 iperf3 -s -i 2

然后运行脚本,也可以打成exe再运行。等待结果然后对比。

```bash
#! /usr/bin/python3.7
# 1. 先ping 192.168.1.154可以ping进入第2步
# 2. telnet 192.168.1.154
# 3. 发送iperf3 cd /tmp ;tftp -gl iperf3 192.168.1.154
# 4. 50M抓取60s,每2s进行一次反馈,最后反馈一个丢包率
# 5. 后期可以改进输入 任意带宽,次数,运行时间,平均丢包率计算
import json
import logging
import time
import telnetlib
import os
import socket

global testIp
global hostIp
port = 23
USER = 'root'
PSW_1 = "root"


# 获取本地网卡的ip地址
def get_ip_address():
    res = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    res.connect(("8.8.8.8", 80))
    return res.getsockname()[0]


# 测试ping连接情况
def pingHost(host):


    status1 = 'PING SUCCESS'
    status2 = 'PING FAILED'
    nowTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    p = os.popen("ping " + host + " -n 2")
    line = p.read()
    if "无法访问目标主机" in line:
        print("***********" + nowTime, host, status2 + "**********")
        return False
    else:
        print("***********" + nowTime, host, status1 + "**********")
        return True


# 等待执行
def wait_read(client, nwait):
    time.sleep(nwait)
    client.readState()


class TelnetClient:
    def __init__(self):
        self.session = telnetlib.Telnet()

    # telnet连接
    def telnet_connect(self, client_addr, port_num):
        try:
            self.session = telnetlib.Telnet(client_addr, port=port_num)
            self.session.open(client_addr, port=port_num)  # telnet默认开启本行注释掉
        except:
            logging.warning('%s网络连接失败' % client_addr)
            return False
        # 延时两秒再收取返回结果,给服务端足够响应时间
        time.sleep(2)
        # 获取登录结果
        # read_very_eager()获取到的是上次获取之后本次获取之前的所有输出
        command_result = self.session.read_very_eager().decode('ascii')
        print('telnet result:', command_result)
        try:
            self.session.read_until(b'cdyctx login:', timeout=2)
            self.session.write(USER.encode('ascii') + b'\n')
            command_result = self.session.read_very_eager().decode('ascii')
            print(command_result)
            time.sleep(2)
            self.session.read_until(b'Password:', timeout=2)
            self.session.write(PSW_1.encode('ascii') + b'\n')
            time.sleep(5)
            command_result = self.session.read_very_eager().decode('ascii')
            print(command_result)

        except:
            logging.warning('telnet 登陆失败')
            return False
        return True

    # telnet 退出登录
    # def logout_telnet(self):
    #     self.session.close()

    def readState(self):
        command_result = self.session.read_very_eager().decode('ascii')
        print(command_result)

    # 执行需要返回值的指令
    def execute_command(self, command, time_wait):
        # 执行命令并且等待
        self.session.write(command + b'\n')
        time.sleep(time_wait)
        # 获取命令结果
        command_result = self.session.read_very_eager().decode('ascii')
        # logging.warning(command + 'execute result:\n %s' % command_result+b'\n')
        print(command_result)
        return command_result


def start_telnet():
    telnet_client = TelnetClient()

    # 1、 telnet连接
    if telnet_client.telnet_connect(testIp, port):
        time.sleep(3)
        telnet_client.execute_command(b'cd /tmp/', 1)
        # print("cd到tmp")
        time.sleep(3)

        # 2、传递tftp文件

        tftp_str = "tftp -gl iperf3 " + get_ip_address()
        telnet_client.execute_command(bytes(tftp_str, "utf-8"), 1)
        wait_read(telnet_client, 1)


        # print('tftp执行')

        # 3、用iperf进行抓包
        wait_read(telnet_client, 1)
        telnet_client.execute_command(b'chmod 777 /tmp/iperf3', 2)
        wait_read(telnet_client, 3)
        test_str = "/tmp/iperf3 -uc " + get_ip_address() + " -b 50M -t 60 -i 2 -w 200K -l 32k"
        telnet_client.execute_command(bytes(test_str, "utf-8"), 3)
        wait_read(telnet_client, 10)
        wait_read(telnet_client, 10)
        wait_read(telnet_client, 10)
        wait_read(telnet_client, 10)
        wait_read(telnet_client, 10)
        wait_read(telnet_client, 10)
        res = telnet_client.session.read_very_eager().decode('ascii')
        for line in res.split():
            if "%" in line:
                print("**********%s*********",line)

        time.sleep(2)
        print("**********抓包完毕*****************")



    else:
        # telnet_client.logout_telnet()
        pass


def start_work():
    ping_result = pingHost(testIp)
    if ping_result:
        # print("*********************PING %s SUCCESS*********************" % updateIp)
        print("***********************START TELNET CONNECT***********************")
        # 可以修改循环的次数!可以连续多次抓包
        for i in range(1,11):
            print("******************第%s次抓包测试***************"%i)
            start_telnet()

    else:
        # print("*********************PING %s FAILED*********************" % updateIp)
        input("*********************PRESS ENTER TO TRY AGAIN**********************")
        start_work()


def go_work():
    if get_ip_address() != "":
        print("********************当前电脑IP:%s *********************" % get_ip_address())
        print("******************************************************************")
        start_work()
    else:
        print("*******************获取电脑IP失败,请检查网络连接*******************")


if __name__ == '__main__':
    # 读取JSON文件,升级目前IP和升级包名
    print("************************自动抓包程序已启动****************************")
    print("********************PRODUCE BY MTY FROM CDYCTX********************")
    print("**********************BUILD DATE 2022-6-8************************")
    print("******************************************************************")
    # 读取json文件
    filepath = os.path.dirname(os.path.realpath(__file__)) + os.sep + "auto.json"
    filepath = filepath.replace("\\", "\\")
    with open(os.getcwd() + os.sep + "auto.json", 'r', encoding="utf-8") as load_f:
        testDic = json.load(load_f)
        testIp = testDic["testIP"]

    print("================== 自动升级抓包已启动成功 ===================")
    if len(testIp) > 0:
        print("\t配置文件读取成功")
        print("\t抓包目标IP地址:", testIp)

        go_work()

    else:
        print("\t配置文件读取失败,请检查目录文件%s%sauto.json" % (os.getcwd(), os.sep))
        print("\t检测文件内容无误后在重新运行本程序")
        input("按回车退出")


  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值