当前位置:   article > 正文

python subprocess run调用net-snmp snmpwalk输出正常解析显示中文

python subprocess run调用net-snmp snmpwalk输出正常解析显示中文
  1. import re
  2. from subprocess import run, PIPE
  3. def bitstring_to_bytes(s):
  4. v = int(s, 2)
  5. b = bytearray()
  6. while v:
  7. b.append(v & 0xff)
  8. v >>= 8
  9. return bytes(b[::-1])
  10. def main():
  11. ipaddress = '127.0.0.1'
  12. oid = '.1.3.6.1.2.1.25.6.3.1'
  13. community = 'public'
  14. port = '161'
  15. host = '{}:{}'.format(ipaddress, port)
  16. timeout = 1000
  17. cmdargs = [
  18. 'snmpwalk', '-Pe', '-t', str(timeout), '-r', '0', '-v', '2c',
  19. '-c', community, host, oid
  20. ]
  21. print(cmdargs)
  22. cmd = run(cmdargs, stdout=PIPE, stderr=PIPE)
  23. if cmd.returncode != 0:
  24. print(cmd.stderr, host)
  25. else:
  26. cmdoutput = cmd.stdout.splitlines()
  27. result = []
  28. for line in cmdoutput:
  29. item = line.decode('utf-8').split(' = ', 1)
  30. if len(item) > 1:
  31. if 'No Such Instance' in item[1]:
  32. item[1] = None
  33. result.append(tuple(item))
  34. else:
  35. prev_item = list(result[-1])
  36. prev_item[1] += '\n' + item[0]
  37. result[-1] = tuple(prev_item)
  38. for row in result:
  39. print(row)
  40. split = row[1].split(':', 2);
  41. if split[0] == 'Hex-STRING':
  42. temp = split[1].replace('\n', '')
  43. temp = temp.replace(' ', '')
  44. hex = re.sub('/[^a-zA-Z0-9]+/', '', temp)
  45. print(hex)
  46. bstr = "{0:08b}".format(int(hex, 16))
  47. print(bitstring_to_bytes(bstr).decode('gbk'))
  48. if __name__ == '__main__':
  49. main()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/218919?site
推荐阅读
相关标签
  

闽ICP备14008679号