命令

    1. adb shell ps

    image.png

    1. 拿到pid

      1. adb shell ps | findstr com.android.browser
    2. image.png

    3. 这边拿到PID:20094然后在去/proc目录下的PID/net/dev面可以看到:
      1. adb shell cat /proc/20094/net/dev
      image.png

    lo :localhost 本地流量
    Receive:接收流量
    Transmit:发送流量

    如果是手机的话
    wlan0代表wifi 上传下载量标识! 上传下载量单位是字节可以/1024换算成KB
    这里可以看到下载的字节数 、数据包 和 发送的字节数 、数据包
    小技巧:wlan0这些值如何初始化0 很简单 你打开手机飞行模式再关掉就清0了

    python 代码

    1. #/usr/bin/python
    2. #encoding:utf-8
    3. import csv
    4. import subprocess
    5. import string
    6. import time
    7. #控制类
    8. class Controller(object):
    9. def __init__(self, count):
    10. #定义测试的次数
    11. self.counter = count
    12. #定义收集数据的数组
    13. self.alldata = [("timestamp", "traffic")]
    14. #单次测试过程
    15. def testprocess(self):
    16. #执行获取进程的命令
    17. result = subprocess.Popen("adb shell ps | findstr com.android.browser",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    18. #获取进程ID
    19. pids = result.stdout.readlines()
    20. pids = pids[0]
    21. pids = pids.decode('utf-8')
    22. pids =pids.split()
    23. pid= pids[1]
    24. #获取进程ID使用的流量
    25. traffic = subprocess.Popen("adb shell cat /proc/"+pid+"/net/dev",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    26. receive=0
    27. transmit=0
    28. receive2=0
    29. transmit2=0
    30. for line in traffic.stdout.readlines():
    31. line = line.decode('utf-8')
    32. if "eth0" in line:
    33. #将所有空行换成#
    34. line = "#".join(line.split())
    35. #按#号拆分,获取收到和发出的流量
    36. receive = line.split("#")[1]
    37. transmit = line.split("#")[9]
    38. elif "eth1" in line:
    39. # 将所有空行换成#
    40. line = "#".join(line.split())
    41. # 按#号拆分,获取收到和发出的流量
    42. receive2 = line.split("#")[1]
    43. transmit2 = line.split("#")[9]
    44. #计算所有流量的之和
    45. alltraffic = int(receive) + int(transmit) + int(receive2) + int(transmit2)
    46. #按KB计算流量值
    47. alltraffic = alltraffic/1024
    48. #获取当前时间
    49. currenttime = self.getCurrentTime()
    50. #将获取到的数据存到数组中
    51. self.alldata.append((currenttime, alltraffic))
    52. #多次测试过程控制
    53. def run(self):
    54. while self.counter >0:
    55. self.testprocess()
    56. self.counter = self.counter - 1
    57. #每5秒钟采集一次数据
    58. time.sleep(5)
    59. #获取当前的时间戳
    60. def getCurrentTime(self):
    61. currentTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    62. return currentTime
    63. #数据的存储
    64. def SaveDataToCSV(self):
    65. csvfile = open('traffic.csv', 'w',encoding='utf-8',newline='')
    66. writer = csv.writer(csvfile)
    67. writer.writerows(self.alldata)
    68. csvfile.close()
    69. if __name__ == "__main__":
    70. controller = Controller(5)
    71. controller.run()
    72. controller.SaveDataToCSV()