kernel_utils.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import re
  2. import socket
  3. import fcntl
  4. import struct
  5. import os
  6. import platform
  7. import subprocess
  8. def _run_cmd_with_output(cmds):
  9. output = []
  10. shell_cmd = ' '.join(cmds)
  11. proc = subprocess.Popen(
  12. shell_cmd,
  13. shell=True,
  14. universal_newlines=True,
  15. stdout=subprocess.PIPE,
  16. stderr=subprocess.STDOUT,)
  17. while True:
  18. line = proc.stdout.readline()
  19. if not line:
  20. break
  21. output.append(line.strip())
  22. proc.wait()
  23. return output
  24. def get_macos_interfaces():
  25. bashCmd = '''networksetup -listallhardwareports| grep Device: |sed -e "s#Device: ##"'''
  26. return _run_cmd_with_output([bashCmd])
  27. def get_linux_interfaces():
  28. return os.listdir('/sys/class/net/')
  29. def get_ip_address(ifname):
  30. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  31. inet = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))
  32. ret = socket.inet_ntoa(inet[20:24])
  33. return ret
  34. def get_all_interfaces():
  35. os = platform.uname()
  36. if not len(os):
  37. return []
  38. if os[0] == 'Darwin':
  39. return get_macos_interfaces()
  40. elif os[0] == 'Linux':
  41. return get_linux_interfaces()
  42. return []
  43. def get_all_ips():
  44. ips = []
  45. for interface in get_all_interfaces():
  46. try:
  47. ip = get_ip_address(interface)
  48. ips.append(ip)
  49. except Exception:
  50. pass
  51. return ips
  52. def is_local_ip(ip):
  53. return ip in get_all_ips()
  54. def is_yunion_kernel():
  55. kernel_str = platform.platform()
  56. pattern = re.compile(r'\.yn[\d]{8}\.')
  57. return pattern.search(kernel_str) is not None