tshark.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #
  2. # tshark module - refactored from test_scan.py
  3. #
  4. # Copyright (c) 2014, Qualcomm Atheros, Inc.
  5. # Copyright (c) 2015, Intel Mobile Communications GmbH
  6. #
  7. # This software may be distributed under the terms of the BSD license.
  8. # See README for more details.
  9. import time
  10. import subprocess
  11. import logging
  12. logger = logging.getLogger()
  13. class UnknownFieldsException(Exception):
  14. def __init__(self, fields):
  15. Exception.__init__(self, "unknown tshark fields %s" % ','.join(fields))
  16. self.fields = fields
  17. _tshark_filter_arg = '-Y'
  18. def _run_tshark(filename, filter, display=None, wait=True):
  19. global _tshark_filter_arg
  20. if wait:
  21. # wait a bit to make it more likely for wlantest sniffer to have
  22. # captured and written the results into a file that we can process here
  23. time.sleep(0.1)
  24. try:
  25. arg = [ "tshark", "-r", filename,
  26. _tshark_filter_arg, filter ]
  27. if display:
  28. arg.append('-Tfields')
  29. for d in display:
  30. arg.append('-e')
  31. arg.append(d)
  32. else:
  33. arg.append('-V')
  34. cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
  35. stderr=subprocess.PIPE)
  36. except Exception, e:
  37. logger.info("Could run run tshark check: " + str(e))
  38. cmd = None
  39. return None
  40. output = cmd.communicate()
  41. out = output[0]
  42. res = cmd.wait()
  43. if res == 1:
  44. errmsg = "Some fields aren't valid"
  45. if errmsg in output[1]:
  46. errors = output[1].split('\n')
  47. fields = []
  48. collect = False
  49. for f in errors:
  50. if collect:
  51. f = f.strip()
  52. if f:
  53. fields.append(f)
  54. continue
  55. if errmsg in f:
  56. collect = True
  57. continue
  58. raise UnknownFieldsException(fields)
  59. # remember this for efficiency
  60. _tshark_filter_arg = '-R'
  61. arg[3] = '-R'
  62. cmd = subprocess.Popen(arg, stdout=subprocess.PIPE,
  63. stderr=open('/dev/null', 'w'))
  64. out = cmd.communicate()[0]
  65. cmd.wait()
  66. return out
  67. def run_tshark(filename, filter, display=None, wait=True):
  68. if display is None: display = []
  69. try:
  70. return _run_tshark(filename, filter, display, wait)
  71. except UnknownFieldsException, e:
  72. all_wlan_mgt = True
  73. for f in e.fields:
  74. if not f.startswith('wlan_mgt.'):
  75. all_wlan_mgt = False
  76. break
  77. if not all_wlan_mgt:
  78. raise
  79. return _run_tshark(filename, filter.replace('wlan_mgt', 'wlan'),
  80. [x.replace('wlan_mgt', 'wlan') for x in display],
  81. wait)